package com.quanyan.place.wrapper.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.enums.CouponOrderType;
import com.quanyan.assets.request.ReqCoupon;
import com.quanyan.assets.request.ReqRuleDetail;
import com.quanyan.assets.response.RespCoupon;
import com.quanyan.assets.response.RespOrderCoupon;
import com.quanyan.assets.response.RespRuleDetail;
import com.quanyan.assets.service.CouponService;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.ServletUtils;
import com.quanyan.common.utils.TimeUtils;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.messagepush.entity.Alert;
import com.quanyan.messagepush.entity.Entry;
import com.quanyan.messagepush.entity.Jump;
import com.quanyan.messagepush.entity.NewBody;
import com.quanyan.messagepush.entity.Payload;
import com.quanyan.messagepush.entity.PushMessage;
import com.quanyan.messagepush.entity.ReqPushMessage;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.IdType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.orderpay.request.ReqOrderCancel;
import com.quanyan.orderpay.request.ReqOrderRefund;
import com.quanyan.orderpay.request.ReqOrderSave;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.orderpay.request.ReqProductDetail;
import com.quanyan.orderpay.request.ReqRefundPayInfo;
import com.quanyan.orderpay.request.ReqRefundProduct;
import com.quanyan.orderpay.request.ReqSysPayInfo;
import com.quanyan.orderpay.request.ReqWithdrawApply;
import com.quanyan.orderpay.request.WithdrawPayInfo;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.component.MerchantClientPayType;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.ExtractCallBackVo;
import com.quanyan.place.entity.apireq.ReqBusinessAccountVo;
import com.quanyan.place.entity.apireq.ReqExtractRecordVo;
import com.quanyan.place.entity.apireq.ReqGetPayInfo;
import com.quanyan.place.entity.apireq.ReqInviteUser;
import com.quanyan.place.entity.apireq.ReqOrderHistory;
import com.quanyan.place.entity.apireq.ReqOrderOperate;
import com.quanyan.place.entity.apireq.ReqOrderPay;
import com.quanyan.place.entity.apireq.ReqOrderSetterVo;
import com.quanyan.place.entity.apireq.ReqOrderShare;
import com.quanyan.place.entity.apireq.ReqPlaceOrderInfo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderListVo;
import com.quanyan.place.entity.apiresp.GoodsInfo;
import com.quanyan.place.entity.apiresp.OrderInfo;
import com.quanyan.place.entity.apiresp.RespAccumulateRule;
import com.quanyan.place.entity.apiresp.RespBusinessAccountVo;
import com.quanyan.place.entity.apiresp.RespCardInfo;
import com.quanyan.place.entity.apiresp.RespInviteUser;
import com.quanyan.place.entity.apiresp.RespOrderDetail;
import com.quanyan.place.entity.apiresp.RespOrderSetterVo;
import com.quanyan.place.entity.apiresp.RespOrderShare;
import com.quanyan.place.entity.apiresp.RespPayInfo;
import com.quanyan.place.entity.apiresp.RespPayInfoList;
import com.quanyan.place.entity.apiresp.RespPlaceOrderDiscountItem;
import com.quanyan.place.entity.apiresp.RespPlaceOrderInfo;
import com.quanyan.place.entity.apiresp.RespPlaceUserInfo;
import com.quanyan.place.entity.apiresp.RespProductUnitInfo;
import com.quanyan.place.entity.dto.OrderHistoryDTO;
import com.quanyan.place.entity.dto.OrderItemCostDTO;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.entity.vo.PlaceTicketPushOrderVo;
import com.quanyan.place.entity.vo.TicketPushOrderVo;
import com.quanyan.place.entity.vo.UnitSalePlan;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.*;
import com.quanyan.place.utils.PlaceOrderUtil;
import com.quanyan.place.wrapper.PlaceMemberWrapper;
import com.quanyan.place.wrapper.PlaceOrderServiceWrapper;
import com.quanyan.sms.service.SmsService;
import com.quanyan.user.request.ReqUserInvite;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.response.RespUserInvite;
import com.quanyan.user.serviceFacade.UserInviteServiceFacade;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sms.SmsApi;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_BASE;
import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

/**
 * Created by Kingson.chan on 2016/6/15 0015.
 */
@Service("placeOrderServiceWrapperImpl")
public class PlaceOrderServiceWrapperImpl implements PlaceOrderServiceWrapper {
    private static final Logger logger = LoggerFactory.getLogger(PlaceOrderServiceWrapperImpl.class);

    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;
    @Autowired
    TbBizPlaceUnitMapper placeUnitMapper;
    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;
    @Autowired
    TbPlaceImageMapper tbPlaceImageMapper;
    @Autowired
    PlaceUnitMapper placeUnitListMapper;
    @Autowired
    PlaceAttachMapper placeAttachMapper;
    @Autowired
    TbBizPlaceUnitTimeMapper tbBizPlaceUnitTimeMapper;
    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;
    @Autowired
    PlaceClient placeClient;
    @Autowired
    TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    PlaceUnitSalePlanMapper placeUnitSalePlanMapper;

    @Autowired
    TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;

    @Autowired
    OrderPayService orderPayService;

    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    UserAssetsService userAssetsService;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;

    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

    @Autowired
    UserService userService;

    @Autowired
    ISearchService searchService;

    @Autowired
    PlaceMapper placeMapper;


    @Value("${c.service.url}")
    public String cAddress;

    @Autowired
    UserInviteServiceFacade userInviteServiceFacade;

    @Autowired
    ClubOpenService clubOpenService;

    @Autowired
    BaseService baseService;

    @Autowired
    IBaseService iBaseService;

    @Autowired
    PlaceMessageService placeMessageService;

    @Autowired
    private PlaceTicketService placeTicketService;

    @Autowired
    private PlaceOrderSetterService placeOrderSetterService;

    @Value("${notify.url.payUrl}")
    private String payUrl;

    @Value("${notify.url.refundUrl}")
    private String refundUrl;

    @Value("${notify.url.exception.refundUrl}")
    private String exceptionRefundUrl;

    @Value("${notify.url.closeOrderUrl}")
    private String closeOrderUrl;

    @Value("${place.share.url}")
    private String placeShareUrl;

    @Value("${place.escape.clause.url}")
    private String placeEscapeClauseUrl;

    @Value("${notify.url.supplierExtractUrl}")
    private String supplierExtractUrl;

    @Autowired
    MqPlaceProductWrapperImpl mqPlaceProductWrapper;

    @Autowired
    PlaceMemberService placeMemberService;

    @Autowired
    TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;

    @Autowired
    SmsService smsService;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;

    @Autowired
    private TbBusinessLogService tbBusinessLogService;
    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    @Autowired
    private TbBizPlacePrivateOrderMapper tbBizPlacePrivateOrderMapper;
    @Autowired
    private TbPlaceTicketStatisticsMapper tbPlaceTicketStatisticsMapper;

    @Autowired
    private ApiPlaceTicketService apiPlaceTicketService;

    @Autowired
    private CouponService couponService;
    @Autowired
    private PlaceMemberWrapper placeMemberWrapper;

    @Autowired
    private TbBizPlaceMemberCardTypeMapper tbBizPlaceMemberCardTypeMapper;

    @Autowired
    private TbBizPlaceUnitCombineMapper pucMapper;

    @Autowired
    private TbBizPlaceUnitSalePlanMapper puspMapper;

    @Autowired
    PlaceOrderCallbackService placeOrderCallbackService;


    @Autowired
    PlaceGoodsService placeGoodsService;

    @Autowired
    PlaceOrderService placeOrderService;

    @Autowired
    PlaceInnerService placeInnerService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    PlaceOrderUtilService placeOrderUtilService;
    @Autowired
    FinanceCommonManagerMapper commonManagerMapper;

    @Autowired
    CagetoryMapper cagetoryMapper;

    @Autowired
    TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

    @Autowired
    FinanceCommonManagerMapper financeCommonManagerMapper;

    @Autowired
    TbBizPlaceOrderHistoryMapper tbBizPlaceOrderHistoryMapper;

    @Autowired
    ApiPlaceOrderService apiPlaceOrderService;

    @Autowired
    PlaceOrderAdminMapper placeOrderAdminMapper;

    @Autowired
    DictMapper dictMapper;
    @Autowired
    TbBizPlaceGoodsInfoMapper tbBizPlaceGoodsInfoMapper;
    @Autowired
    CommonService commonService;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    @Override
    public APIResponse<RespPlaceOrderInfo> preOrder(ReqPlaceOrderListVo reqPlaceOrderListVo) {
        //预下单验证
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        reqPlaceOrderListVo.setUid(userId);
        APIResponse apiResponse = null;
        apiResponse = preOrderVerification(reqPlaceOrderListVo);
        if( apiResponse != null){
            return apiResponse;
        }

        //从数据库查询订场信息
        List<String> values = new ArrayList<>();
        List<UnitSalePlan> unitSalePlanIdList = reqPlaceOrderListVo.getUnitSalePlanIdList();
        for (UnitSalePlan unitSalePlan : unitSalePlanIdList) {
            values.add(unitSalePlan.getSaleId());
        }
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria = example.createCriteria();
        tbBizPlaceUnitSalePlanCriteria.andSaleIdIn(values);
        tbBizPlaceUnitSalePlanCriteria.andPlaceIdEqualTo(reqPlaceOrderListVo.getPlaceId());
        tbBizPlaceUnitSalePlanCriteria.andCategoryIdEqualTo(reqPlaceOrderListVo.getCategoryId());
        example.setOrderByClause("place_unit_name,start_time");//按照场地名称、销售计划开始时间排序，+0将MySQL字符串字段按数值排序

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper.selectByExample(example);

        if(CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanList)){
            return APIResponse.returnFail("不存在该销售计划！");
        }

        // 注意这里要考虑到子场被多次包含的问题
        apiResponse = null;
        apiResponse = salePlansVerification(tbBizPlaceUnitSalePlanList);
        if (apiResponse != null) {
            return apiResponse;
        }

        //竞拍、约运动业务需要进行验证：只能订一个场地，定义为一个连续时间段，否则报错
        if(PlaceConstants.SOURCE_TYPE_AUCTIONPAY.equals(reqPlaceOrderListVo.getSourceType()) || PlaceConstants.SOURCE_TYPE_SPORT.equals(reqPlaceOrderListVo.getSourceType())){
            apiResponse = auctionPayVerification(tbBizPlaceUnitSalePlanList);
            if( apiResponse != null){
                return apiResponse;
            }
        }


        //获取会员卡列表
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = placeMemberService.getPlaceMemberInfo(reqPlaceOrderListVo.getUid(), reqPlaceOrderListVo.getPlaceId(), reqPlaceOrderListVo.getCategoryId(),false);

        RespPlaceOrderInfo respPlaceOrderInfo = new RespPlaceOrderInfo();
        respPlaceOrderInfo.setEscapeClauseUrl(placeEscapeClauseUrl);

        List<String> placeDateTimeList = new ArrayList<>();
        //生成预下单信息
        List<RespProductUnitInfo> productUnits = new ArrayList<>();
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            RespProductUnitInfo respProductUnitInfo = new RespProductUnitInfo();
            respProductUnitInfo.setStartTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()));
            respProductUnitInfo.setEndTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));
            respProductUnitInfo.setPlaceUnitName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
            respProductUnitInfo.setCategoryId(tbBizPlaceUnitSalePlan.getCategoryId());
            respProductUnitInfo.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
            respProductUnitInfo.setPrice(tbBizPlaceUnitSalePlan.getPrice());
            respProductUnitInfo.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            respProductUnitInfo.setDate(tbBizPlaceUnitSalePlan.getDate());
            productUnits.add(respProductUnitInfo);
            respPlaceOrderInfo.setOrderMemberAmount(tbBizPlaceUnitSalePlan.getMemberPrice().add(respPlaceOrderInfo.getOrderMemberAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
            respPlaceOrderInfo.setOrderAmount(tbBizPlaceUnitSalePlan.getPrice().add(respPlaceOrderInfo.getOrderAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
            respPlaceOrderInfo.setCategoryName(iBaseService.getCommonDataCache("cagetory" + tbBizPlaceUnitSalePlan.getCategoryId().toString()));
            respPlaceOrderInfo.setPlaceId(tbBizPlaceUnitSalePlan.getPlaceId());
            String date = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());
            respPlaceOrderInfo.setDate(date);

            respPlaceOrderInfo.setWeek(DateUtils.dayForWeek(date));

            /**获取优惠券信息需要检查场地的是时间段是否匹配**/
            placeDateTimeList.add(date + " " +DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime())+","+
                    date + " " +DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));

        }
        respPlaceOrderInfo.setProductUnits(productUnits);
        TbBizPlace tbBizPlace = placeBaseService.getPlaceById(respPlaceOrderInfo.getPlaceId());
        //验证场馆是否下架，如果已下架，则不允许执行预下单流程 is_shelves ：0：下架 1：上架',
        Integer isShelves = tbBizPlace.getIsShelves();
        if (null != isShelves && isShelves.equals(0)){
            return APIResponse.returnFail("该场馆已下架，请重新选择其他场馆！");
        }
        //TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(respPlaceOrderInfo.getPlaceId());// TODO 可以从缓存中获取
        respPlaceOrderInfo.setPlaceName(tbBizPlace.getName());
        respPlaceOrderInfo.setSubjectURL(tbBizPlace.getBizPlaceUrl());


        //设置用户可用的支付信息，需要支付系统提供，微信只返回公众号支付信息
        List<RespPayInfo> payInfos = new ArrayList<>();
        List<RespCardInfo> cardInfos = new ArrayList<>();

        if(reqPlaceOrderListVo.getPayInfoType() == null){
            reqPlaceOrderListVo.setPayInfoType(0);
        }
        ReqSysPayInfo reqSysPayInfo = new ReqSysPayInfo();
        reqSysPayInfo.setSourceSystemId(PlaceConstants.PLACE_SYSTEM_CODE);
        reqSysPayInfo.setSourceBusinessId(PlaceConstants.BUSINESS_CODE_PAYINFO_PREFIX + reqPlaceOrderListVo.getPayInfoType());
        APIResponse<List<com.quanyan.orderpay.response.RespPayInfo>> listAPIResponse = this.orderPayService.selectEnablePayInfos(reqSysPayInfo);
        List<com.quanyan.orderpay.response.RespPayInfo> respPayInfos = listAPIResponse.getData();

        //TODO 上线时如果发现没有相关支付类型，需要给不同支付类型进行初始化设置
        if(CollectionUtils.isEmpty(respPayInfos)){
            ReqSysPayInfo reqSysPayInfoReg = new ReqSysPayInfo();
            List<Integer> ids = new ArrayList<>();
            switch (reqPlaceOrderListVo.getPayInfoType()){
                case 0:
                    ids.add(1);
                    ids.add(2);
                    break;
                default:
                    ids.add(reqPlaceOrderListVo.getPayInfoType());break;
            }

            //初始化
            reqSysPayInfoReg.setPayIds(ids);
            reqSysPayInfoReg.setSourceSystemId(PlaceConstants.PLACE_SYSTEM_CODE);
            reqSysPayInfoReg.setSourceBusinessId(PlaceConstants.BUSINESS_CODE_PAYINFO_PREFIX + reqPlaceOrderListVo.getPayInfoType());
            this.orderPayService.applyEnablePayInfos(reqSysPayInfoReg);

            //再次查询
            ReqSysPayInfo reqSysPayInfoRetry = new ReqSysPayInfo();
            reqSysPayInfoRetry.setSourceSystemId(PlaceConstants.PLACE_SYSTEM_CODE);
            reqSysPayInfoRetry.setSourceBusinessId(PlaceConstants.BUSINESS_CODE_PAYINFO_PREFIX + reqPlaceOrderListVo.getPayInfoType());
            listAPIResponse = this.orderPayService.selectEnablePayInfos(reqSysPayInfoRetry);
            respPayInfos = listAPIResponse.getData();
        }


        try {
            for (com.quanyan.orderpay.response.RespPayInfo respPayInfo : respPayInfos) {
                RespPayInfo respPayInfoTemp = new RespPayInfo();
                BeanUtils.copyProperties(respPayInfo,respPayInfoTemp);
                payInfos.add(respPayInfoTemp);
            }

            if(CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList)){
                for (TbBizPlaceMemberCard tbBizPlaceMemberCard : tbBizPlaceMemberCardList) {
                   /* if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == tbBizPlaceMemberCard.getCardType() ||  PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT == tbBizPlaceMemberCard.getCardType()){
                        // TODO 过滤次卡和储值折扣卡（以后会放开储值折扣卡）
                        continue;
                    }*/
                    RespCardInfo respCardInfo = new RespCardInfo();
                    if (tbBizPlaceMemberCard.getDeadLineTime() != null
                            && tbBizPlaceMemberCard.getDeadLineTime().getTime() < new Date().getTime()){
                        continue;
                    }

                    BeanUtils.copyProperties(tbBizPlaceMemberCard, respCardInfo);
                    //增加会员卡类型
                    TbBizPlaceMemberCardType tbBizPlaceMemberCardType = this.tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(tbBizPlaceMemberCard.getCardTypeId());
                    if (!org.springframework.util.StringUtils.isEmpty(tbBizPlaceMemberCardType)){
                        tbBizPlaceMemberCardType.setDescription(null);
                        respCardInfo.setTbBizPlaceMemberCardType(tbBizPlaceMemberCardType);
                    }
                    respCardInfo.setSourceType(tbBizPlaceMemberCard.getSourceType());
                    respCardInfo.setBalance(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()));
                    respCardInfo.setAvailableStartTime(DateTimeUtils.timeToStr(tbBizPlaceMemberCard.getAvailableStartTime()));
                    respCardInfo.setAvailableEndTime(DateTimeUtils.timeToStr(tbBizPlaceMemberCard.getAvailableEndTime()));
                    respCardInfo.setIsOldMember(tbBizPlaceMemberCard.getIsOldMember());
                    cardInfos.add(respCardInfo);
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

        //场馆自营才返回鸟蛋和优惠券信息
        if(tbBizPlace.getBusinessMode() != null && PlaceConstants.BUSINESS_MODE_SELF_SUPPORT.equals(tbBizPlace.getBusinessMode())){
            //设置积分兑换规则列表，需要积分系统提供
            com.quanyan.api.APIRequest<ReqRuleDetail> apiRequest = new  com.quanyan.api.APIRequest<>();
            ReqRuleDetail reqRuleDetail = new ReqRuleDetail();
            reqRuleDetail.setUid(reqPlaceOrderListVo.getUid());
            reqRuleDetail.setBusinessCode(Constants.PLACE_BOOKING_CODE);
            reqRuleDetail.setSystemCode(Constants.PLACE_SYSTEM_CODE);
            reqRuleDetail.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
            reqRuleDetail.setOrderAmount(respPlaceOrderInfo.getOrderAmount());
            apiRequest.setData(reqRuleDetail);
            APIResponse<List<RespRuleDetail>>  respRuleDetailAPIResponse = null;
            try {
                respRuleDetailAPIResponse = userAssetsService.getUserAccumulateAndRule(apiRequest);
            } catch (Exception e) {
                logger.warn("uid：{} ，error：{} ", reqPlaceOrderListVo.getUid(), e.getMessage());
                //throw new BizException(PlaceErrorCodeEnum.ASSETS_SYSTEM_ERROR);
            }
            if(respRuleDetailAPIResponse!= null){
                if (!respRuleDetailAPIResponse.isRet()){
                    logger.warn("uid：{} ，error：{} ", reqPlaceOrderListVo.getUid(), respRuleDetailAPIResponse.getErrmsg());
                    //throw new BizException(PlaceErrorCodeEnum.ASSETS_SYSTEM_ERROR);
                }
                if (null != respRuleDetailAPIResponse.getData()){
                    List<RespRuleDetail> respRuleDetailList = respRuleDetailAPIResponse.getData();
                    if(CollectionUtils.isNotEmpty(respRuleDetailList)){
                        RespRuleDetail respRuleDetail = respRuleDetailList.get(0);
                        List<RespAccumulateRule> accumulateRuleList = new ArrayList<>();
                        RespAccumulateRule respAccumulateRule = new RespAccumulateRule();
                        respAccumulateRule.setAmount(respRuleDetail.getExchangeRMB());
                        respAccumulateRule.setPayId(PlaceConstants.PAY_WAY_FOR_AGES);
                        respAccumulateRule.setName("鸟蛋抵扣");
                        respAccumulateRule.setDescribe("-￥" + respRuleDetail.getExchangeRMB() + "（消耗" + respRuleDetail.getUseAccumulate() + "鸟蛋）");
                        accumulateRuleList.add(respAccumulateRule);
                        respPlaceOrderInfo.setAccumulateRuleList(accumulateRuleList);
                    } else {
                        List<RespAccumulateRule> accumulateRuleList = new ArrayList<>();
                        RespAccumulateRule respAccumulateRule = new RespAccumulateRule();
                        respAccumulateRule.setAmount(new BigDecimal(0));
                        respAccumulateRule.setPayId(PlaceConstants.PAY_WAY_FOR_AGES);
                        respAccumulateRule.setName("鸟蛋抵扣");
                        respAccumulateRule.setDescribe("-￥0（消耗0鸟蛋）");
                        accumulateRuleList.add(respAccumulateRule);
                        respPlaceOrderInfo.setAccumulateRuleList(accumulateRuleList);
                    }
                }
            }

            //获取优惠券列表
            APIRequest<ReqCoupon> apiReqCouponRequest = new APIRequest<>();
            ReqCoupon reqCoupon = new ReqCoupon();
            reqCoupon.setUid(userId);
            reqCoupon.setSportType(tbBizPlaceUnitSalePlanList.get(0).getCategoryId().byteValue());
            reqCoupon.setOrderType(CouponOrderType.PLACE.getId().byteValue());
            reqCoupon.setEnabledAmount(respPlaceOrderInfo.getOrderAmount());
            reqCoupon.setCityId(tbBizPlace.getCityId());//优惠券添加城市
            reqCoupon.setPlaceId(tbBizPlace.getId());
            reqCoupon.setPageSize(100);

            reqCoupon.setPlaceDateTimeList(placeDateTimeList);

            apiReqCouponRequest.setVer(reqPlaceOrderListVo.getVer());//设置版本号
            /*if (null != tbBizPlaceMemberCardList && tbBizPlaceMemberCardList.size()>0){
                reqCoupon.setPaymethod((byte)1);
            }*/
            apiReqCouponRequest.setData(reqCoupon);

            APIResponse<RespOrderCoupon> apiCouponResponse = null;
            try {
                apiCouponResponse = couponService.getOrderCouponList(apiReqCouponRequest);
                if(apiCouponResponse.isRet()){
                    RespOrderCoupon respOrderCoupon = apiCouponResponse.getData();
                    respPlaceOrderInfo.setRespOrderCoupon(respOrderCoupon);
                }
                else {
                    logger.info("获取优惠券列表失败：" + apiCouponResponse.getErrmsg());
                }
            } catch (Exception e) {
                e.printStackTrace();
                //throw new BizException(PlaceErrorCodeEnum.COUPON_SYSTEM_ERROR);
            }

        } else {
            // 兼容老版本
            PageObj<List<RespCoupon>> pageObj = new PageObj<List<RespCoupon>>();
            pageObj.setItems(new ArrayList<RespCoupon>());
            RespOrderCoupon respOrderCoupon = new RespOrderCoupon();
            respOrderCoupon.setPageObj(pageObj);
            respPlaceOrderInfo.setRespOrderCoupon(respOrderCoupon);
            List<RespAccumulateRule> accumulateRuleList = new ArrayList<>();
            RespAccumulateRule respAccumulateRule = new RespAccumulateRule();
            respAccumulateRule.setAmount(new BigDecimal(0));
            respAccumulateRule.setPayId(PlaceConstants.PAY_WAY_FOR_AGES);
            respAccumulateRule.setName("鸟蛋抵扣");
            respAccumulateRule.setDescribe("-￥0（消耗0鸟蛋）");
            accumulateRuleList.add(respAccumulateRule);
            respPlaceOrderInfo.setAccumulateRuleList(accumulateRuleList);
        }
        respPlaceOrderInfo.setPayInfos(payInfos);
        respPlaceOrderInfo.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        respPlaceOrderInfo.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        //设置是否为自营场馆  经营方式 1：自营 2：联营
        respPlaceOrderInfo.setPlaceBusinessCode(tbBizPlace.getBusinessMode());
        //会员使用时段验证
        if(CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList)){
            memberPayVerification(tbBizPlaceUnitSalePlanList,cardInfos,respPlaceOrderInfo);
            respPlaceOrderInfo.setCardInfos(cardInfos);
        }

        return APIResponse.returnSuccess(respPlaceOrderInfo);
    }

    /**
     *竞拍业务需要进行验证：只能订一个场地，定义为一个连续时间段，否则报错
     * @param tbBizPlaceUnitSalePlanListTemp
     * @return
     */
    private APIResponse auctionPayVerification(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanListTemp){
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = new ArrayList<>();
        tbBizPlaceUnitSalePlanList.addAll(tbBizPlaceUnitSalePlanListTemp);
        if(tbBizPlaceUnitSalePlanList.size() > 1){//预定场次大于1再进行验证
            Comparator<TbBizPlaceUnitSalePlan> comparator = new Comparator<TbBizPlaceUnitSalePlan>() {
                @Override
                public int compare(TbBizPlaceUnitSalePlan o1, TbBizPlaceUnitSalePlan o2) {
                    return o1.getStartTime().compareTo(o2.getStartTime());
                }
            };
            Collections.sort(tbBizPlaceUnitSalePlanList, comparator);//按照开始时间排序
            for (int i = 0; i < tbBizPlaceUnitSalePlanList.size(); i++) {
                if(!tbBizPlaceUnitSalePlanList.get(0).getPlaceUnitId().equals(tbBizPlaceUnitSalePlanList.get(i).getPlaceUnitId())){
                    return APIResponse.returnFail("只能预订一个场地！");
                }
            }

            for (int i = 0; i < tbBizPlaceUnitSalePlanList.size()-1; i++) {
                try {
                    String startTime =DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlanList.get(i).getStartTime());
                    String endTime =DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlanList.get(i+1).getStartTime());
                    if(TimeUtils.timeToHour(TimeUtils.subtractTime(startTime,endTime)) > 1){//时差大于一小时，说明不连续
                        return APIResponse.returnFail("预定的场地时段必须为连续时间段！");
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    @Override
    public APIResponse<RespPreOrder> pay(ReqPlaceOrderInfo reqPlaceOrderInfo) {
        //用户验证
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        String ver = httpServletRequest.getHeader("APPVersion");
        reqPlaceOrderInfo.setAPPVersion(ver);
        reqPlaceOrderInfo.setUid(userId);
        reqPlaceOrderInfo.setItemUuid(UUIDUtils.createId());
        APIResponse apiResponse = null;

        //todo 这个验证有问题
        apiResponse = payUserVerification(reqPlaceOrderInfo);
        if( apiResponse != null){
            return apiResponse;
        }
        //下单验证
        apiResponse = orderVerification(reqPlaceOrderInfo);
        if( apiResponse != null && !apiResponse.isRet()){
            return apiResponse;
        }

        List<ReqPayInfo> payInfos = reqPlaceOrderInfo.getPayInfos();
        Iterator<ReqPayInfo> it = payInfos.iterator();

        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
        reqPlaceOrderListVo.setUnitSalePlanIdList(reqPlaceOrderInfo.getUnitSalePlanIdList());
        reqPlaceOrderListVo.setUid(reqPlaceOrderInfo.getUid());
        reqPlaceOrderListVo.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        reqPlaceOrderListVo.setCategoryId(reqPlaceOrderInfo.getCategoryId());
        reqPlaceOrderListVo.setPreStatus(PlaceConstants.PLACE_PREORDER_STATUS);

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = null;



        //锁定库存，返回销售计划信息
        //如果是会员卡，则销售计划状态为3
        if(payInfos.size() == 1 && PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfos.get(0).getPayId())){
            tbBizPlaceUnitSalePlanList = placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_ORDER_STATUS);
            String errorString = "";
            if(CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)){
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                    if(!tbBizPlaceUnitSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)){
                        errorString = tbBizPlaceUnitSalePlan.getPlaceUnitName() + "的" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime())+"时段已经售出！";
                        return APIResponse.returnFail(errorString);
                    }
                }
            }
            else {
                return APIResponse.returnFail("不存在该销售计划，订场无效！");
            }
        }else{
            //否则走微信或支付宝流程，
            tbBizPlaceUnitSalePlanList = placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_LOCk_STATUS);
            String errorString = "";
            if(CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)){
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                    if(!tbBizPlaceUnitSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)){
                        errorString = tbBizPlaceUnitSalePlan.getPlaceUnitName() + "的" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime())+"时段已经售出！";
                        return APIResponse.returnFail(errorString);
                    }
                }
            }
            else {
                return APIResponse.returnFail("不存在该销售计划，订场无效！");
            }
        }

        // TODO  查询场馆信息，可以从缓存中获取
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqPlaceOrderInfo.getPlaceId());
        reqPlaceOrderInfo.setCityId(tbBizPlace.getCityId());

        /**获取优惠券信息添加时间段信息**/
        List<String> placeDateTimeList = new ArrayList<>();

        BigDecimal debit = new BigDecimal(0);
        BigDecimal vipDebit = new BigDecimal(0);
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            debit = debit.add(tbBizPlaceUnitSalePlan.getPrice());//获取真实的订单总价
            vipDebit = vipDebit.add(tbBizPlaceUnitSalePlan.getMemberPrice());
            /**获取优惠券信息需要检查场地的是时间段是否匹配**/
            String date = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());
            placeDateTimeList.add(date + " " +DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime())+","+
                    date + " " +DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));

        }


        if (reqPlaceOrderInfo.getIsVipPay().intValue() == 1){
            debit = vipDebit;
        }
        try {
            if(debit.compareTo(new BigDecimal(0)) == 0){
                throw  new BizException(PlaceErrorCodeEnum.ORDER_MONEY_IS_ZERO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BizException(PlaceErrorCodeEnum.ORDER_MONEY_IS_ZERO);
        }


        //向资产系统获取到用户鸟蛋，H5不需要获取
        BigDecimal eggs = new BigDecimal(0).setScale(0);
        BigDecimal moneyOfEggs = new BigDecimal(0);
        BigDecimal couponDebit = new BigDecimal(0);
        boolean couponUseFlag = false;
        boolean onlyUseCouponPay = false;

        //校验是否使用优惠券
        boolean couponType = false;
        RespCoupon respCoupon = null;
        for (ReqPayInfo payInfo : payInfos) {
            if(PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfo.getPayId())){
                APIResponse<RespCoupon> apiCouponResponse = null;
                try {
                    apiCouponResponse = couponService.getInfoByCode(payInfo.getSubjectCode());
                    if(apiCouponResponse.isRet()){
                        respCoupon = apiCouponResponse.getData();
                        //couponDebit = respCoupon.getCouponAmount();
                        if (null ==  payInfo.getAmount()){
                            couponDebit = respCoupon.getCouponAmount();
                        }else{
                            couponDebit = payInfo.getAmount();
                        }
                        couponUseFlag = true;
                        /**判断是折扣券还是抵扣券**/
                        if (respCoupon.getCouponType().equals((byte)2)){
                            couponType = true;
                            couponDebit = payInfo.getAmount();
                        }
                        /**优惠券添加订场时间段**/
                        payInfo.setPlaceDateTimeList(placeDateTimeList);
                    }
                    else {
                        logger.info("获取优惠券信息失败：" + apiCouponResponse.getErrmsg());
                        throw new BizException(PlaceErrorCodeEnum.COUPON_SYSTEM_ERROR);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BizException(PlaceErrorCodeEnum.COUPON_SYSTEM_ERROR);
                }

            }
        }

        //是否只使用优惠券支付
        if(payInfos.size() == 1 && couponUseFlag){
            onlyUseCouponPay = true;
        }

        //校验是否使用鸟蛋
        for (ReqPayInfo payInfo : payInfos) {
            if(PlaceConstants.PAY_WAY_FOR_AGES.equals(payInfo.getPayId())){
                com.quanyan.api.APIRequest<ReqRuleDetail> apiRequest = new com.quanyan.api.APIRequest<>();
                ReqRuleDetail reqRuleDetail = new ReqRuleDetail();
                reqRuleDetail.setUid(reqPlaceOrderInfo.getUid());
                reqRuleDetail.setBusinessCode(Constants.PLACE_BOOKING_CODE);
                reqRuleDetail.setSystemCode(Constants.PLACE_SYSTEM_CODE);
                reqRuleDetail.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
                if(couponUseFlag){
                    reqRuleDetail.setOrderAmount(debit.subtract(couponDebit).setScale(2,BigDecimal.ROUND_HALF_UP));
                }
                else {
                    reqRuleDetail.setOrderAmount(debit);
                }

                apiRequest.setData(reqRuleDetail);
                APIResponse<List<RespRuleDetail>>  respRuleDetailAPIResponse = null;
                try {
                    respRuleDetailAPIResponse = userAssetsService.getUserAccumulateAndRule(apiRequest);
                    if(respRuleDetailAPIResponse == null || !respRuleDetailAPIResponse.isRet()){
                        throw new BizException(PlaceErrorCodeEnum.ASSETS_SYSTEM_ERROR);
                    }
                }
                catch (Exception e){
                    if(respRuleDetailAPIResponse != null && !respRuleDetailAPIResponse.isRet()){
                        logger.warn("uid：{} ，error：{} " ,reqPlaceOrderInfo.getUid(),respRuleDetailAPIResponse.getErrmsg());
                    }
                    else {
                        logger.warn("uid：{} ，error：{} " ,reqPlaceOrderInfo.getUid(),e.getMessage());
                    }
                    throw new BizException(PlaceErrorCodeEnum.ASSETS_SYSTEM_ERROR);
                }

                List<RespRuleDetail> respRuleDetailList = respRuleDetailAPIResponse.getData();
                if(CollectionUtils.isNotEmpty(respRuleDetailList)){
                    RespRuleDetail respRuleDetail = respRuleDetailList.get(0);
                    eggs = new BigDecimal(respRuleDetail.getUseAccumulate()).setScale(0);
                    moneyOfEggs = respRuleDetail.getExchangeRMB();
                }
            }

        }

        debit = debit.setScale(2,BigDecimal.ROUND_HALF_UP);
        while (it.hasNext()){//删除支付金额为0的支付类型
            ReqPayInfo payInfo = it.next();
            if(PlaceConstants.PAY_WAY_FOR_AGES.equals(payInfo.getPayId())){
                payInfo.setAmount(eggs);
            }
            else if(PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfo.getPayId())){
                /**为兼容老版本，普通支付及优惠券折扣，当优惠券金额为0，提示升级最新版本**/
                BigDecimal amount = payInfo.getAmount();
                if (null != amount){
                    int r = amount.compareTo(BigDecimal.ZERO);
                    if (r == 0){
                        throw new BizException(PlaceErrorCodeEnum.COUPON_DISCOUNT_PAY_ERROR);
                        //return APIResponse.returnFail(PlaceErrorCodeEnum.COUPON_DISCOUNT_PAY_ERROR);
                    }
                    if (r != 0){
                        payInfo.setAmount(amount);
                    }
                }else {
                    int  c = couponDebit.compareTo(BigDecimal.ZERO);
                    if (c == 0){
                        throw new BizException(PlaceErrorCodeEnum.COUPON_DISCOUNT_PAY_ERROR);
                        //return APIResponse.returnFail(PlaceErrorCodeEnum.COUPON_DISCOUNT_PAY_ERROR);
                    }
                    if (c != 0){
                        payInfo.setAmount(couponDebit);
                    }
                }
                payInfo.setSportType(reqPlaceOrderInfo.getCategoryId().byteValue());
                payInfo.setSubjectCode(respCoupon.getCouponCode());
                payInfo.setOrderType(CouponOrderType.PLACE.getId().byteValue());
                payInfo.setPlaceId(reqPlaceOrderInfo.getPlaceId());
                payInfo.setCityId(reqPlaceOrderInfo.getCityId());
            }
            else {
                if(couponUseFlag){
                    BigDecimal money = debit.subtract(moneyOfEggs).setScale(2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal temp = money.subtract(couponDebit).setScale(2,BigDecimal.ROUND_HALF_UP);
                    payInfo.setAmount(temp);
                }
                else {
                    BigDecimal money = debit.subtract(moneyOfEggs).setScale(2,BigDecimal.ROUND_HALF_UP);
                    payInfo.setAmount(money);
                }

            }
            if(payInfo.getAmount().compareTo(new BigDecimal(0)) == 0){
                it.remove();
            }
        }

        if(payInfos.size() == 1 && PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfos.get(0).getPayId())){
            /**抵扣券**/
            if (!couponType){
                if (reqPlaceOrderInfo.getIsVipPay().intValue() == 1 ){
                    debit = vipDebit;
                }
                if (couponDebit.compareTo(debit) >= 0){
                    payInfos.get(0).setAmount(debit);
                    payInfos.get(0).setSportType(reqPlaceOrderInfo.getCategoryId().byteValue());
                    payInfos.get(0).setSubjectCode(respCoupon.getCouponCode());
                    payInfos.get(0).setOrderType(CouponOrderType.PLACE.getId().byteValue());
                    payInfos.get(0).setPlaceId(reqPlaceOrderInfo.getPlaceId());
                    payInfos.get(0).setCityId(reqPlaceOrderInfo.getCityId());
                    logger.info("抵扣券支付："+JSON.toJSONString(payInfos));
                }else{
                    logger.debug("抵扣券支付："+JSON.toJSONString(payInfos));
                    return APIResponse.returnFail("抵扣券支付金额不足"+couponDebit);
                }
            }

        }

        reqPlaceOrderInfo.setOrderAmount(debit);

        // 获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM,reqPlaceOrderInfo.getUid());
        reqPlaceOrderInfo.setOrderNo(orderNo);

        /**设置服务开关
         * ServiceSwitch 0:不支持，1:支持
         * **/
        TbCommonParameter parameter1 = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
        if (parameter1 != null && parameter1.getParameterValue() != null) {
            reqPlaceOrderInfo.setServiceSwitch(Integer.valueOf(parameter1.getParameterValue()));
        }

        if (reqPlaceOrderInfo.getServiceSwitch().equals(0)) {
            //插入订单明细表
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
                tbBizPlaceOrderItem.setPlaceOrderId(orderNo);
                tbBizPlaceOrderItem.setUnitSalePlanId(tbBizPlaceUnitSalePlan.getId());
                tbBizPlaceOrderItem.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
                tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getPrice());
                tbBizPlaceOrderItem.setVersion(tbBizPlaceUnitSalePlan.getVersion());
                tbBizPlaceOrderItem.setTicketCount(1);
                tbBizPlaceOrderItem.setConsumeTime(tbBizPlaceUnitSalePlan.getDate());//消费日期

                tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
                tbBizPlaceOrderItem.setUseType((byte) 3);
                tbBizPlaceOrderItem.setGoodsId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                tbBizPlaceOrderItem.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
                tbBizPlaceOrderItem.setSurplusGoodsCount(1);
                tbBizPlaceOrderItem.setTotalGoodsCount(1);
                tbBizPlaceOrderItem.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
                tbBizPlaceOrderItem.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());
                tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceUnitSalePlan.getPrice());
                tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
                tbBizPlaceOrderItem.setCategoryId(reqPlaceOrderInfo.getCategoryId());
                tbBizPlaceOrderItemMapper.insertSelective(tbBizPlaceOrderItem);
            }

            //插入订单支付方式明细表
            if (CollectionUtils.isNotEmpty(payInfos)) {
                for (ReqPayInfo payInfo : payInfos) {
                    TbBizPlacePayItem record = new TbBizPlacePayItem();
                    record.setPlaceOrderId(orderNo);
                    record.setAmount(payInfo.getAmount());
                    record.setPayType(payInfo.getPayId());
                    record.setAmountType(PlaceConstants.DEBIT_TYPE);
                    if (PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfo.getPayId())) {
                        record.setSubjectCode(payInfo.getSubjectCode());
                    }
                    record.setAdminPayType(PlaceOrderUtil.getAdminPayType(payInfo.getPayId()));

                    tbBizPlacePayItemMapper.insertSelective(record);
                }
            }
        }

        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
        tbBizPlaceOrder.setUid(reqPlaceOrderInfo.getUid());
        if (null != reqPlaceOrderInfo.getUid()){
            /**获取用户基本信息**/
            APIResponse<RespUserInfoDetail> userInfoDetail = userServiceFacade.queryUserInfoDetail(reqPlaceOrderInfo.getUid());
            if (null != userInfoDetail){
                RespUserInfoDetail userInfo= userInfoDetail.getData();
                if (null != userInfo){
                    tbBizPlaceOrder.setCustomerName(userInfo.getNickName());
                    tbBizPlaceOrder.setMobile(userInfo.getMobile());
                }
            }
        }else{
            tbBizPlaceOrder.setCustomerName("散客");
        }

        Date date = new Date();
        tbBizPlaceOrder.setPlaceOrderId(orderNo);
        tbBizPlaceOrder.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        tbBizPlaceOrder.setCategoryId(reqPlaceOrderInfo.getCategoryId());
        tbBizPlaceOrder.setDate(date);
        tbBizPlaceOrder.setDebit(debit);
        tbBizPlaceOrder.setOrderTime(date);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.NOT_PAY_STATUS);
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PREPAY_STATUS);
        tbBizPlaceOrder.setDescrible(reqPlaceOrderInfo.getDescribe());
        tbBizPlaceOrder.setCreateTime(date);
        tbBizPlaceOrder.setOrderStatusChangeDate(date);
        tbBizPlaceOrder.setPlatform(reqPlaceOrderInfo.getPlatformType());
        tbBizPlaceOrder.setOrderUse(PlaceConstants.NO);
        tbBizPlaceOrder.setIsEffective(PlaceConstants.YES);
        tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_APP_BILLING);
        tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());//场馆
        if(reqPlaceOrderInfo.getIsVipPay().intValue() ==1){//TODO
            tbBizPlaceOrder.setIsMember((byte)1);
        }else{
            tbBizPlaceOrder.setIsMember((byte)0);
        }

         /**1:IOS 2:Android3:微信4.普通浏览器6.QQ7:微信小程序**/
        int platformType = reqPlaceOrderInfo.getPlatformType().intValue();
        Byte sourceType = PlaceOrderUtil.orderSourceTypeByPlatform(platformType);
        if (null != sourceType){
            tbBizPlaceOrder.setSourceType(sourceType);
        }
        Byte orderChannel = PlaceOrderUtil.orderChannelByPlatform(platformType);
        if (null != orderChannel){
            tbBizPlaceOrder.setOrderChannel(orderChannel);
        }

        //设置回调方式
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_ORDER_CALLBACK_TYPE.getCode());
        Integer callbackType = 0;
        if (parameter != null && parameter.getParameterValue() != null){
            callbackType = Integer.valueOf(parameter.getParameterValue());
        }
        reqPlaceOrderInfo.setCallbackType(callbackType);
        reqPlaceOrderInfo.setTradeType((byte)0);
        reqPlaceOrderInfo.setUseType(PlaceConstants.ORDER_USE_APP_BILLING);

        if (reqPlaceOrderInfo.getServiceSwitch().equals(1)) {
            /**拆分订单明细**/
            OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
            orderItemCostDTO.setOrderType(1);
            orderItemCostDTO.setPayInfoList(payInfos);
            orderItemCostDTO.setTbBizPlaceUnitSalePlanList(tbBizPlaceUnitSalePlanList);
            orderItemCostDTO.setReqPlaceOrderInfo(reqPlaceOrderInfo);
            orderItemCostDTO.setRespCoupon(respCoupon);
            
            //1.写入订单明细
            APIResponse orderItemCostResp = apiPlaceOrderService.setOrderItemCostService(orderItemCostDTO);
            if (null != orderItemCostResp) {
                return APIResponse.returnFail("订单明细执行异常！");
            }
            
            //2.写入支付明细
            APIResponse payItemResp = apiPlaceOrderService.setOrderPayItemCostService(orderItemCostDTO);
            if (null != payItemResp) {
                return APIResponse.returnFail("付款明细执行异常！");
            }
            
            /**
             * 普通支付且只有一种支付方式则不参与优惠
             */
            if (reqPlaceOrderInfo.getPayInfos().size() == 1 && PlaceOrderUtil.getMapPayId().contains(reqPlaceOrderInfo.getPayInfos().get(0).getPayId())){
                /**不做操作**/
            }else{
            	//3.写入优惠明细
                APIResponse orderDiscount = apiPlaceOrderService.setOrderDiscountItemCostService(orderItemCostDTO);
                if (null != orderDiscount) {
                    return APIResponse.returnFail("折扣优惠明细执行异常！");
                }
            }

          
        }
        //通知订单系统，生成订单，需要抛出异常
        RespPreOrder respPreOrder = null;
        APIResponse<RespPreOrder> respPreOrderAPIResponse = null;
        try {
            respPreOrderAPIResponse = noticeOrderSystem(reqPlaceOrderInfo, tbBizPlace, tbBizPlaceUnitSalePlanList,false);
            //存储订单系统的订单号
            if(respPreOrderAPIResponse != null && respPreOrderAPIResponse.isRet()){
                respPreOrder = respPreOrderAPIResponse.getData();
                /** USER_PAY_SUCCESS **/
                if (com.quanyan.pay.enums.OrderStatusEnum.USER_PAY_SUCCESS.getCode().equals(respPreOrder.getResult())){
                    tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
                    tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
                    tbBizPlaceOrder.setPaymentTime(date);
                    reqPlaceOrderInfo.setIsSendMsg(1);
                }
                tbBizPlaceOrder.setOrderNo(respPreOrder.getOrderNo());
                tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);
            } else {
                throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
            }
        }
        catch (Exception e){
            logger.info("uid：{"+userId+"}，订场下单支付error：{"+e.getMessage()+"}");
            if(respPreOrderAPIResponse != null && !respPreOrderAPIResponse.isRet()){
                logger.error("uid：{} ，orderNo: {} ，error：{} ", reqPlaceOrderInfo.getUid(), reqPlaceOrderInfo.getOrderNo(), respPreOrderAPIResponse.getErrmsg());
            }
            else {
                logger.error("uid：{} ，orderNo: {} ，error：{} ", reqPlaceOrderInfo.getUid(), reqPlaceOrderInfo.getOrderNo(), e.getMessage());
            }

            if (respPreOrderAPIResponse.getErrcode() == 21012){
                throw new BizException(PlaceErrorCodeEnum.TICKET_PAY_CONFIG_ERROR);
            }

            if ("该优惠券不能使用".equals(respPreOrderAPIResponse.getErrmsg())){
                throw new BizException(PlaceErrorCodeEnum.COUPON_NOT_USE);
            }

            throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
        }

        //加入redis队列
        /*OrderDetailCacheVo orderDetailCacheVo = new OrderDetailCacheVo();
        orderDetailCacheVo.setTbBizPlaceOrder(tbBizPlaceOrder);
        orderDetailCacheVo.setTbBizPlaceUnitSalePlanList(tbBizPlaceUnitSalePlanList);
        placeRedisTemplate.lpush(getOrderCacheQueueName(), orderDetailCacheVo);*/
        if (reqPlaceOrderInfo.getIsSendMsg().intValue() == 1){
            ReqOrderOperate orderOperate = new ReqOrderOperate();
            orderOperate.setOperateType(2);
            orderOperate.setOrderNo(reqPlaceOrderInfo.getOrderNo());
            orderOperate.setPlaceId(reqPlaceOrderInfo.getPlaceId());
            orderCallBackHistory(orderOperate);
        }


        return APIResponse.returnSuccess(respPreOrder);
    }

    private List<TbBizPlaceOrder>  selectPlaceOrderByOrderId(String placeOrderId){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbPlaceOrder = tbBizPlaceOrderExample.createCriteria();
        tbPlaceOrder.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        return tbBizPlaceOrders;
    }
    private int insertOrderRecordHistory(ReqOrderOperate reqOrderOperate) {
        List<ReqPayInfo> payInfos = reqOrderOperate.getPayInfoList();
        boolean result = false;
        int returnResult = 0;
        BigDecimal orderAmount = null;
        if (null != payInfos && payInfos.size() > 0) {
            for (ReqPayInfo payInfo : payInfos) {
                if (PlaceConstants.PAY_WAY_ALIPAY.equals(payInfo.getPayId()) ||
                        PlaceConstants.PAY_WAY_WEICHAT.equals(payInfo.getPayId()) ||
                        PlaceConstants.PAY_WAY_WEICHATH5.equals(payInfo.getPayId()) ||
                        PlaceConstants.PAY_WAY_FOR_WEB_ALIPAY.equals(payInfo.getPayId()) ||
                        PlaceConstants.PAY_WAY_FOR_WEIXIN_APPLET.equals(payInfo.getPayId())) {
                    result = true;
                    orderAmount = payInfo.getAmount();
                    break;
                }
            }
        }
        List<TbBizPlaceOrder> tbBizPlaceOrders = selectPlaceOrderByOrderId(reqOrderOperate.getOrderNo());
        if (null == tbBizPlaceOrders || tbBizPlaceOrders.isEmpty()) {
            return returnResult;
        }
        if (result) {
            TbBizPlaceOrderHistory tbBizPlaceOrderHistory = new TbBizPlaceOrderHistory();
            String placeOrderId = reqOrderOperate.getOrderNo();
            tbBizPlaceOrderHistory.setAmount(orderAmount);
            if(reqOrderOperate.getOperateType().intValue() == 1 || reqOrderOperate.getOperateType().intValue() == 4){ //支付成功
                tbBizPlaceOrderHistory.setBusinessType((byte)0);
            }
            if (reqOrderOperate.getOperateType().intValue() == 2 ){ //退款
                tbBizPlaceOrderHistory.setBusinessType((byte)1);
            }
            tbBizPlaceOrderHistory.setCreateTime(new Date());
            tbBizPlaceOrderHistory.setPlaceId(tbBizPlaceOrders.get(0).getPlaceId());
            tbBizPlaceOrderHistory.setPlatform(tbBizPlaceOrders.get(0).getPlatform());
            tbBizPlaceOrderHistory.setSourceType(PlaceConstants.SOURCE_TYPE_COMMONPAY);//普通支付
            tbBizPlaceOrderHistory.setPlaceOrderId(placeOrderId);
            if (tbBizPlaceOrders.get(0).getUseType().equals((byte) 2)) {//门票
                tbBizPlaceOrderHistory.setUseType(tbBizPlaceOrders.get(0).getUseType());
            } else if (tbBizPlaceOrders.get(0).getUseType().equals((byte) 3)) {//app开单
                tbBizPlaceOrderHistory.setUseType(tbBizPlaceOrders.get(0).getUseType());
            }
            ReqOrderHistory reqOrderHistory = new ReqOrderHistory();
            BeanUtils.copyProperties(tbBizPlaceOrderHistory, reqOrderHistory);
            try {
                placeOrderUtilService.insertOrderHistory(reqOrderHistory);
            } catch (Exception e) {
                logger.debug("insertOrderRecordHistory：插入失败");
                e.printStackTrace();
            }
        }
        return returnResult;

    }
    /**
     * 获取redis订单缓存队列名称，每个jvm进程消费自己的队列数据，避免队列资源消费出现锁冲突
     * @return
     */
    public static String getOrderCacheQueueName(){
        //TODO  只有请求才能获取ip和端口号，后台任务获取不了，需要改进
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        return PlaceConstants.PLACE_ORDER_CACHE_QUEUE_PREFIX + httpServletRequest.getLocalAddr() + "_" +httpServletRequest.getLocalPort();
    }


    private APIResponse payUserVerification(ReqPlaceOrderInfo reqPlaceOrderInfo){
        //获取用户信息
        if(reqPlaceOrderInfo.getUid() != null && reqPlaceOrderInfo.getUserInfo() == null){
            APIResponse<RespUserInfoBase> result = userServiceFacade.queryUserInfo(reqPlaceOrderInfo.getUid());
            if(!result.isRet()){
                return APIResponse.returnFail("不存在该用户！");
            }
            RespPlaceUserInfo respPlaceUserInfo = new RespPlaceUserInfo();
            try {
                BeanUtils.copyProperties(result.getData(), respPlaceUserInfo);
            }
            catch (Exception e){
                e.printStackTrace();
                return APIResponse.returnFail("服务器异常！");
            }
            reqPlaceOrderInfo.setUserInfo(respPlaceUserInfo);
        }
        return null;
    }


    /**
     *根据用户一天取消订单数、退订单数等验证用户是否可以下单
     * @param reqPlaceOrderInfo
     * @return
     */

    private APIResponse orderVerification(ReqPlaceOrderInfo reqPlaceOrderInfo){
        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqPlaceOrderInfo.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList =  tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        Map<String,String> placeOrderRuleMap = baseService.getPlaceOrderRule();
        int PLACE_PLAN_MAX_CLOSE = 0;//场馆一天最大取消订场次数
        int PLACE_ALL_ORDER_MAX_TIME = 0;//用户一天可预定最大的时段总数
        int PLACE_PLAN_MAX_PAYING = 0; //用户场地预定的最大未支付订单条数

        PLACE_PLAN_MAX_CLOSE = Integer.parseInt(placeOrderRuleMap.get("MAX_CANCEL_ORDRE_NUM"));//场馆一天最大取消订场次数
        PLACE_PLAN_MAX_PAYING = Integer.parseInt(placeOrderRuleMap.get("MAX_NON_PAYMENT_ORDER_NUM"));//用户场地预定的最大未支付订单条数
        if(CollectionUtils.isEmpty(tbBizPlaceRuleList)){
            PLACE_ALL_ORDER_MAX_TIME = PlaceConstants.PLACE_ALL_ORDER_MAX_TIME;
            logger.info("下单验证规则从默认配置中获取，placeId={}",reqPlaceOrderInfo.getPlaceId());
        }
        else {
            TbBizPlaceRule tbBizPlaceRule = tbBizPlaceRuleList.get(0);
            PLACE_ALL_ORDER_MAX_TIME = tbBizPlaceRule.getAllOrderMaxTime();//用户一天可预定最大的时段总数
        }

        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andUidEqualTo(reqPlaceOrderInfo.getUid());
        tbBizPlaceOrderCriteria.andOrderStatusChangeDateEqualTo(new Date());
        List<Byte> values = new ArrayList<>();
        values.add(PlaceConstants.ORDER_CLOSE_STATUS);
        values.add(PlaceConstants.ORDER_PREPAY_STATUS);
        tbBizPlaceOrderCriteria.andOrderStatusIn(values);

        int PLACE_PLAN_CLOSE_COUNT = 0;
        int PLACE_PLAN_PAYING_COUNT = 0;


        List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if(CollectionUtils.isNotEmpty(placeOrderList)){
            for (TbBizPlaceOrder tbBizPlaceOrder : placeOrderList) {
                if(PlaceConstants.ORDER_PREPAY_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
                    PLACE_PLAN_PAYING_COUNT++;
                }
                if(PlaceConstants.ORDER_CLOSE_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
                    PLACE_PLAN_CLOSE_COUNT++;
                }
            }

            //判断用户是否已经取消两次订单
            if (PLACE_PLAN_CLOSE_COUNT >= PLACE_PLAN_MAX_CLOSE) {
                return APIResponse.returnFail("您一天之内已经取消订单"+PLACE_PLAN_MAX_CLOSE+"次，不能再下单，请明天再进行预定！");
            }
            //判断用户是否有两条未完成的订单，如果存在，提示用户支付
            if (PLACE_PLAN_PAYING_COUNT >= PLACE_PLAN_MAX_PAYING) {
                return APIResponse.returnFail("您有" + PLACE_PLAN_MAX_PAYING + "条未完成的订单，请先完成付款！");
            }

        }

        //获取订单总的销售计划小时
        Integer ORDER_SALE_PLAN_ALL_HOURS = tbBizPlaceOrderManagerMapper.countSalePlanHours(reqPlaceOrderInfo);

        Map<String,Object> map = new HashMap<>();
        map.put("date",DateUtils.transferDateToString(new Date()));
        map.put("uid",reqPlaceOrderInfo.getUid());
        map.put("placeId",reqPlaceOrderInfo.getPlaceId());

        //获取已经购买的销售计划小时数（统计用户当天下单的总的销售计划小时数，订单状态为未付款、已付款、已完成）
        int USER_ALL_ORDER_MAX_TIME = tbBizPlaceOrderManagerMapper.countUserPayOrderAllTimeByDay(map);
        if( (USER_ALL_ORDER_MAX_TIME + ORDER_SALE_PLAN_ALL_HOURS > PLACE_ALL_ORDER_MAX_TIME) && (PLACE_ALL_ORDER_MAX_TIME > USER_ALL_ORDER_MAX_TIME)){
            Integer REMAINED_HOURS = PLACE_ALL_ORDER_MAX_TIME - USER_ALL_ORDER_MAX_TIME;
            return APIResponse.returnFail("该场馆您只能再预定" + REMAINED_HOURS + "小时！" );
        }
        if(USER_ALL_ORDER_MAX_TIME + ORDER_SALE_PLAN_ALL_HOURS > PLACE_ALL_ORDER_MAX_TIME){
            return APIResponse.returnFail("您已经超过一天可预定最大的时段总数：" +PLACE_ALL_ORDER_MAX_TIME + "小时！" );
        }

        return null;
    }

    /**
     * 检验用户下单数目是否超过一次下单可预定最大的时段数
     * @param reqPlaceOrderListVo
     * @return
     */
    private APIResponse preOrderVerification(ReqPlaceOrderListVo reqPlaceOrderListVo){
        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqPlaceOrderListVo.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList =  tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        int PLACE_ONCE_ORDER_MAX_TIME = 0;
        if(CollectionUtils.isEmpty(tbBizPlaceRuleList)){
            // return APIResponse.returnFail("不存在该场馆信息！");
            PLACE_ONCE_ORDER_MAX_TIME = PlaceConstants.PLACE_ONCE_ORDER_MAX_TIME;

        }
        else {
            TbBizPlaceRule tbBizPlaceRule = tbBizPlaceRuleList.get(0);
            PLACE_ONCE_ORDER_MAX_TIME = tbBizPlaceRule.getOnceOrderMaxTime();//用户一次可预定最大的时段总数
        }

        List<String> salePlanIdValues = new ArrayList<>();
        List<UnitSalePlan> unitSalePlanIdList = reqPlaceOrderListVo.getUnitSalePlanIdList();
        for (UnitSalePlan unitSalePlan : unitSalePlanIdList) {
            salePlanIdValues.add(unitSalePlan.getSaleId());
        }
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria = example.createCriteria();
        tbBizPlaceUnitSalePlanCriteria.andSaleIdIn(salePlanIdValues);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper.selectByExample(example);

        double USER_ONCE_ORDER_MAX_TIME = 0;
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            try {
                String subtractTime = TimeUtils.subtractTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()),DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));
                USER_ONCE_ORDER_MAX_TIME += TimeUtils.timeToHour(subtractTime);
            }
            catch (Exception e){
                e.printStackTrace();
                return APIResponse.returnFail("系统异常！");
            }
        }
        if(USER_ONCE_ORDER_MAX_TIME > PLACE_ONCE_ORDER_MAX_TIME){
            return APIResponse.returnFail("最多能选择" +PLACE_ONCE_ORDER_MAX_TIME + "个场次！" );

        }
        return null;
    }

    private APIResponse<RespPreOrder> noticeOrderSystem(ReqPlaceOrderInfo reqPlaceOrderInfo,TbBizPlace tbBizPlace,List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList,boolean isVip){
        logger.info("noticeOrderSystem(ReqPlaceOrderInfo reqPlaceOrderInfo--->"+JSON.toJSONString(reqPlaceOrderInfo));
        com.quanyan.api.APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new com.quanyan.api.APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();

        reqOrderSave.setSourceBusinessId(Constants.PLACE_BOOKING_CODE);
        reqOrderSave.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
        reqOrderSave.setPlatformType(reqPlaceOrderInfo.getPlatformType());//设置平台类型
        reqOrderSave.setContactMobile(reqPlaceOrderInfo.getUserInfo().getMobile());
        reqOrderSave.setContactName(reqPlaceOrderInfo.getUserInfo().getNickName());
        reqOrderSave.setExtraParam("");
        if(reqPlaceOrderInfo.getCityId() != null && reqPlaceOrderInfo.getCityId().equals(3)){
            reqOrderSave.setMchId(3); //此处为城市ID，必填
        }else {
            reqOrderSave.setMchId(2); //此处为城市ID，必填
        }
        //微信小程序
        Integer mchId = reqPlaceOrderInfo.getMchId();
        if (null != mchId){
            reqOrderSave.setMchId(mchId);
        }

        //如果回调类型为0，则订单系统使用http方式进行回调；如果回调类型为1，使用mq进行处理
        if(reqPlaceOrderInfo.getCallbackType().equals(Constants.IS_NO)){
            reqOrderSave.setNotifyURL(payUrl);
            reqOrderSave.setCloseNotifyURL(closeOrderUrl);
            reqOrderSave.setRefundNotifyURL(refundUrl);
            reqOrderSave.setExceptionRefundNotify(exceptionRefundUrl);
            logger.info("订单号：{}，支付使用http回调处理。",reqPlaceOrderInfo.getOrderNo());
        }
        else {
            logger.info("订单号：{}，支付使用mq消息处理。",reqPlaceOrderInfo.getOrderNo());
        }
        //
        if(isVip){
            List<ReqPayInfo> requestPayInfo = reqPlaceOrderInfo.getPayInfos();
            if (requestPayInfo.size() == 1 && requestPayInfo.get(0).getPayId().equals(PlaceConstants.PAY_WAY_FOR_CARD)){
                reqOrderSave.setOrderAmount(reqPlaceOrderInfo.getPayInfos().get(0).getAmount());
            }else{
                for (ReqPayInfo reqPayInfo : requestPayInfo) {
                    if (reqPayInfo.getPayId().equals(PlaceConstants.PAY_WAY_FOR_COUPON) || reqPayInfo.getPayId().equals(PlaceConstants.PAY_WAY_FOR_CARD)){
                        reqOrderSave.setOrderAmount(reqPlaceOrderInfo.getOrderAmount());
                        break;
                    }
                }
            }
        }else {
            reqOrderSave.setOrderAmount(reqPlaceOrderInfo.getOrderAmount());
        }

        reqOrderSave.setOrderDescribe("预定" + tbBizPlace.getName());
        reqOrderSave.setOrderURL(tbBizPlace.getBizPlaceUrl());
        reqOrderSave.setOutTradeNo(reqPlaceOrderInfo.getOrderNo());
        reqOrderSave.setPayNote("");
        reqOrderSave.setUserClientIp("");
        reqOrderSave.setPayTimeOut(PlaceConstants.PAYTIMEOUT);
        reqOrderSave.setUid(reqPlaceOrderInfo.getUserInfo().getUid());
        reqOrderSave.setShowURL(reqPlaceOrderInfo.getSubjectURL());
        reqOrderSave.setEggInfo(tbBizPlace.getName() + "订场费");
        reqOrderSave.setEggReceiver("百灵鸟");
        reqOrderSave.setVer(reqPlaceOrderInfo.getVer());//设置版本号
        if (!org.springframework.util.StringUtils.isEmpty(reqPlaceOrderInfo.getReturnUrlForH5())){
            reqOrderSave.setReturnUrlForH5(reqPlaceOrderInfo.getReturnUrlForH5());
        }
        if (!org.springframework.util.StringUtils.isEmpty(reqPlaceOrderInfo.getShowURLForH5())){
            reqOrderSave.setShowURLForH5(reqPlaceOrderInfo.getShowURLForH5());
        }
        if(reqPlaceOrderInfo.getOpenId() != null){
            reqOrderSave.setBuyerAccount(reqPlaceOrderInfo.getOpenId());
        }
        else {
            reqOrderSave.setBuyerAccount("");
        }

        reqOrderSave.setService(PlaceConstants.SERVICE_CODE);


        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            ReqProductDetail reqProductDetail = new ReqProductDetail();
            reqProductDetail.setShowURL(tbBizPlace.getBizPlaceUrl());
            if(isVip){
                reqProductDetail.setPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            }
            else {
                reqProductDetail.setPrice(tbBizPlaceUnitSalePlan.getPrice());
            }
            reqProductDetail.setProductDesc(tbBizPlace.getName());
            reqProductDetail.setProductId(tbBizPlaceUnitSalePlan.getSaleId());
            reqProductDetail.setProductName(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime())+"时段");
            reqProductDetail.setProductURL(tbBizPlace.getBizPlaceUrl());
            reqProductDetail.setQuantity(1);
            reqProductDetailList.add(reqProductDetail);
        }

        reqOrderSave.setProductDetailList(reqProductDetailList);
        reqOrderSave.setPayInfos(reqPlaceOrderInfo.getPayInfos());
        reqOrderSave.setLarkAppId(reqPlaceOrderInfo.getLarkAppId());
        reqOrderSaveAPIRequest.setData(reqOrderSave);
        logger.info("orderPayService.submitOrder--->"+JSON.toJSONString(reqOrderSaveAPIRequest));
        APIResponse<RespPreOrder> respPreOrderAPIResponse = orderPayService.submitOrder(reqOrderSaveAPIRequest);
        return respPreOrderAPIResponse;
    }

    /**
     * 检验销售计划有没有重叠
     * @param tbBizPlaceUnitSalePlanList
     * @return
     */
    public APIResponse salePlansVerification(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList) {
        Set<String> uniqSaleIds = new HashSet<>();

        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            List<String> saleIds = new ArrayList<>();

            if (tbBizPlaceUnitSalePlan == null) {
                continue;
            }

            String saleId = tbBizPlaceUnitSalePlan.getSaleId();
            if (saleId != null) {
                saleIds.add(saleId);
            }

            if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
                String subSaleplans = tbBizPlaceUnitSalePlan.getSubSaleplans();
                List<String> subSaleplanIds = new ArrayList<>();
                if (subSaleplans != null) {
                    subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
                }

                if (subSaleplanIds != null && subSaleplanIds.size() > 0) {
                    saleIds.addAll(subSaleplanIds);
                }
            }

            for (String curSaleId : saleIds) {
                if (uniqSaleIds.contains(curSaleId)) {
                    return APIResponse.returnFail("销售计划" + saleId + "有重叠！" );
                } else {
                    uniqSaleIds.add(curSaleId);
                }
            }
        }

        return null;
    }

    @Override
    public APIResponse<?> orderOperate(ReqOrderOperate reqOrderOperate) {
        if(PlaceConstants.ORDER_CANCEL_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCancelOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_COMPLETE_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCompletePayOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_UNSUBSCRIBE_OPERATE.equals(reqOrderOperate.getOperateType())){//申请退款
            return orderUnsubscribeOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_COMPLETE_UNSUBSCRIBE_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCompleteUnsubscribeOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_CANCEL_TO_UNSUBSCRIBE_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCancleToUnsubscribeOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_PAY_CONFIRM_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderPayConfirmOperate(reqOrderOperate);
        }
        return APIResponse.returnFail("订单处理类型参数输入错误！");
    }



    /**
     * 订单取消处理
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCancelOperate(ReqOrderOperate reqOrderOperate){
        //订单取消验证
        if(PlaceConstants.YES.equals(reqOrderOperate.getIsCallBackOrder())){
            HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
            Integer userId = (Integer)httpServletRequest.getAttribute("uid");
            if(userId != null && userId != 0 ){
                reqOrderOperate.setUid(userId);
            }
        }

        APIResponse apiResponse = orderCancelOperateVerification(reqOrderOperate);
        if(apiResponse != null){
            return apiResponse;
        }

        String orderNo = reqOrderOperate.getOrderNo();
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());

        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = null;
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = null;
        if (tbBizPlaceOrder==null){
            tbBizPlacePrivateOrder = getBizPlacePrivateOrder(orderNo);
            if (tbBizPlacePrivateOrder!=null){
                //包场取消回调
                return placeOrderCallbackService.bookAllOrderCancelOperate(reqOrderOperate);
            }
            tbBizPlaceMemberOpHistory = getBizPlaceMemberHistory(orderNo);
            if (tbBizPlaceMemberOpHistory!=null){
                //会员开卡和充值  防止订单系统反复回调return success
                return APIResponse.returnSuccess("会员卡业务成功！");
            }
            return APIResponse.returnFail("没有该条订单信息！");
        }

        //商家端门票取消回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)
                && tbBizPlaceOrder.getOrderChannel() == 4){
            return placeOrderCallbackService.ticketOrderCancelOperate(reqOrderOperate);
        }
        //场馆订单如果为门票，走门票逻辑
        if(tbBizPlaceOrder.getUseType() != null && tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return apiPlaceTicketService.orderCancelOperate(reqOrderOperate);
        }
        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCancelOperate(reqOrderOperate);
        }*/
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderCallbackService.billingOrderCancelOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderCallbackService.goodsOrderCancelOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderCallbackService.shoppingCartOrderCancelOperate(reqOrderOperate);
        }

        //判断订单状态为付款中状态，销售计划状态为正在预定状态
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            if(PlaceConstants.ORDER_PREPAY_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){

                //通知订单系统，订单已经被取消
                if(PlaceConstants.YES.equals(reqOrderOperate.getIsCallBackOrder())){
                    logger.info("通知订单系统关闭订单，订单号：{}",reqOrderOperate.getOrderNo());
                    APIRequest<ReqOrderCancel> orderCancelAPIRequest = new APIRequest<>();
                    ReqOrderCancel reqOrderCancel = new ReqOrderCancel();
                    reqOrderCancel.setOrderNo(placeOrderSalePlanList.get(0).getOrderNo());
                    reqOrderCancel.setOutTradeNo(placeOrderSalePlanList.get(0).getPlaceOrderId());
                    reqOrderCancel.setUid(reqOrderOperate.getUid());
                    reqOrderCancel.setSourceBusinessId(PlaceConstants.PLACE_BUSINESS_CODE);
                    reqOrderCancel.setSourceSystemId(Constants.PLACE_SYSTEM);
                    reqOrderCancel.setCancelReason(reqOrderOperate.getReason());
                    reqOrderCancel.setVer(reqOrderOperate.getVer());
                    //区分操作APP通过larkAppId
                    reqOrderCancel.setLarkAppId(reqOrderOperate.getLarkAppId());

                    orderCancelAPIRequest.setData(reqOrderCancel);

                    APIResponse<BaseEnum> apiResponseOrderCancel = this.orderPayService.orderCancel(orderCancelAPIRequest);
                    if(apiResponseOrderCancel == null || !apiResponseOrderCancel.isRet()){
                        return APIResponse.returnFail("订单取消失败，请重试！");
                    }
                }

                //设置订单状态为已经关闭状态，释放库存
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                reqPlaceOrderListVo.setUid(null);//清理uid
                reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
                List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    UnitSalePlan unitSalePlan = new UnitSalePlan();
                    unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
                    unitSalePlanIdList.add(unitSalePlan);
                }
                reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
                placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

                //设置订单状态为关闭状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                TbBizPlaceOrder record = new TbBizPlaceOrder();
                record.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
                record.setOrderStatusChangeDate(new Date());
                record.setEndTime(new Date());
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

                //更改订单支付明细的状态为取消状态
                TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                tbBizPlacePayItem.setAmountType(PlaceConstants.CANCEL_TYPE);
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,tbBizPlacePayItemExample);

                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter != null && parameter.getParameterValue() != null) {
                    if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }

                //释放场地状态更新场地价格
                try {
                    placeInnerService.syncSalePlanPriceForRefundOrder(reqOrderOperate.getOrderNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return APIResponse.returnSuccess("订单取消成功！");
            }
            else if(PlaceConstants.ORDER_CLOSE_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){
                return APIResponse.returnSuccess("订单取消已经受理！");
            }
            else {
                logger.warn("订单取消异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单取消异常！");
            }
        }
        return APIResponse.returnFail("没有该条订单信息！");
    }

    /**
     * 用户取消订单验证
     * @param reqOrderOperate
     * @return
     */
    private APIResponse orderCancelOperateVerification(ReqOrderOperate reqOrderOperate){
        if(PlaceConstants.ORDER_OPERATE_APPUSER.equals(reqOrderOperate.getUserType())){
            Map<String,String> placeOrderRuleMap = baseService.getPlaceOrderRule();
            int PLACE_PLAN_MAX_CLOSE = 0;
            PLACE_PLAN_MAX_CLOSE = Integer.parseInt(placeOrderRuleMap.get("MAX_CANCEL_ORDRE_NUM"));//场馆一天最大取消订场次数
            TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
            tbBizPlaceOrderCriteria.andUidEqualTo(reqOrderOperate.getUid());
            tbBizPlaceOrderCriteria.andOrderStatusChangeDateEqualTo(new Date());
            tbBizPlaceOrderCriteria.andOrderStatusEqualTo(PlaceConstants.ORDER_CLOSE_STATUS);
            List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
            if(CollectionUtils.isNotEmpty(placeOrderList)){
                if (placeOrderList.size() >= PLACE_PLAN_MAX_CLOSE) {
                    return APIResponse.returnFail("您一天之内已经取消订单" + PLACE_PLAN_MAX_CLOSE + "次，不能再取消！");
                }
            }
        }
        return null;
    }

    /**
     * 如果支付系统完成支付，进行订单回调处理
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCompletePayOperate(ReqOrderOperate reqOrderOperate){
        //需要进行权限限制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");

        }

        String orderNo = reqOrderOperate.getOrderNo();

        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(orderNo);

        if (tbBizPlaceOrder!=null){
            if (!tbBizPlaceOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
            	return APIResponse.returnFail("订单不是未支付状态！");
            }
        }
        
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = null;
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = null;
        if (tbBizPlaceOrder==null){
            tbBizPlacePrivateOrder = getBizPlacePrivateOrder(orderNo);
            if (tbBizPlacePrivateOrder!=null){
                if (!tbBizPlacePrivateOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlacePrivateOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                	return APIResponse.returnFail("订单不是未支付状态！");
                }
                //包场支付回调
                return placeOrderCallbackService.bookAllOrderCompletePayOperate(reqOrderOperate);
            }
            tbBizPlaceMemberOpHistory = getBizPlaceMemberHistory(orderNo);
            if (tbBizPlaceMemberOpHistory!=null){
                if (!tbBizPlaceMemberOpHistory.getState().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO)){
                	return APIResponse.returnFail("开卡充值记录不是未支付状态！");
                }
                //商家端会员卡扫码支付充值回调
                if (tbBizPlaceMemberOpHistory.getPayType().toString().equals(PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN)
                        || tbBizPlaceMemberOpHistory.getPayType().toString().equals( PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN)||tbBizPlaceMemberOpHistory.getPayType().toString().equals( PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY)){//add by tim,增加银联pos支付
                    return placeOrderCallbackService.cardOrderCompletePayOperate(reqOrderOperate);
                }
                //app会员卡开卡充值回调
                if (tbBizPlaceMemberOpHistory.getPayType() == PlaceConstants.PAY_WAY_ALIPAY
                        || tbBizPlaceMemberOpHistory.getPayType() == PlaceConstants.PAY_WAY_WEICHAT){
                    return placeOrderCallbackService.appCardChargeOrderCompletePayOperate(reqOrderOperate, tbBizPlaceMemberOpHistory);
                }
            }
            return APIResponse.returnFail("没有该条订单信息！");
        }
        //商家端门票支付成功回调
        if (tbBizPlaceOrder.getSourceType().equals(PlaceConstants.SOURCE_TYPE_SCENEPAY)
                &&tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderCallbackService.ticketOrderCompletePayOperate(reqOrderOperate);
        }
        //门票支付回调
        if(tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            reqOrderOperate.setPlaceId(tbBizPlaceOrder.getPlaceId());
            return orderCompleteTicketOperate(reqOrderOperate);
        }

       /* if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCompletePayOperate(reqOrderOperate, tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCompletePayOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单包场回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                ||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
            return placeOrderCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderCallbackService.goodsOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderCallbackService.shoppingCartOrderCompletePayOperate(reqOrderOperate);
        }


        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());
        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {

            if (PlaceConstants.ORDER_PREPAY_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                //将销售计划表状态设置为已经预定状态
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                reqPlaceOrderListVo.setUid(reqOrderOperate.getUid());
                reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
                List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    UnitSalePlan unitSalePlan = new UnitSalePlan();
                    unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
                    unitSalePlanIdList.add(unitSalePlan);
                }
                reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
                placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

                //设置订单状态为已经付款状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
                tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                TbBizPlaceOrder record = new TbBizPlaceOrder();
                record.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
                record.setPayStatus(PlaceConstants.PAY_STATUS);
                Date date = new Date();
                record.setOrderStatusChangeDate(date);
                record.setPaymentTime(reqOrderOperate.getPayTime());
                record.setEndTime(date);
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample1);

                //馆报名人数加一
                Map<String,Object> map = new HashMap<>();
                map.put("placeId", placeOrderSalePlanList.get(0).getPlaceId());
                map.put("addSignupCount", 1);
                placeMapper.updateCount(map);

                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                List<Integer>  payTypeList = PlaceOrderUtil.getPayType();
                tbBizPlacePayItemCriteria.andPayTypeIn(payTypeList);
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                    APIResponse.returnFail("没有该条订单信息！");
                }

                //加入消息推送，提示订场成功
                PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(1);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setPayType(tbBizPlacePayItemList.get(0).getPayType());
                Cagetory cagetory =cagetoryMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getCategoryId());
                placeMessage.setCategoryValue(cagetory.getName());

                boolean result = pushMessageOperate(placeMessage);
                //加入消息队列进行异步消息推送处理，场馆系统自己作为生产者也作为消费者。
                if(!result){
                    mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
                }
                commonService.mqSendSportService(reqOrderOperate.getOrderNo(),1);
                //发送短信
                smsSendOperate(placeOrderSalePlanList, null, reqOrderOperate.getUid(), tbBizPlace);
               // insertOrderRecordHistory(reqOrderOperate);
                /**支付系统完成**/
                orderCallBackHistory(reqOrderOperate);
                /*//发送mq消息给运动场业务
                PlaceOrderVo placeOrderVo = new PlaceOrderVo();
                placeOrderVo.setUid(reqOrderOperate.getUid());
                placeOrderVo.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeOrderVo.setCategoryId(placeOrderSalePlanList.get(0).getCategoryId());
                placeOrderVo.setPlaceOrderId(reqOrderOperate.getOrderNo());
                List<PlaceOrderProduct> placeOrderProductList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    PlaceOrderProduct placeOrderProduct = new PlaceOrderProduct();
                    placeOrderProduct.setEndTime(placeOrderSalePlan.getEndTime());
                    placeOrderProduct.setStartTime(placeOrderSalePlan.getStartTime());
                    placeOrderProduct.setPlaceUnitId(placeOrderSalePlan.getPlaceUnitId());
                    placeOrderProduct.setPlaceUnitName(placeOrderSalePlan.getPlaceUnitName());
                    placeOrderProductList.add(placeOrderProduct);
                }
                placeOrderVo.setType(1);
                placeOrderVo.setPlaceOrderProductList(placeOrderProductList);
                mqPlaceProductWrapper.sendOrderInfoToStadium(placeOrderVo);*/

                /*try {
                    this.searchService.addPlaceIndex(tbBizPlace, null);
                } catch (Exception e) {
                    logger.error("增加索引失败，加入消息队列进行处理!");
                    //加入消息队列进行异步索引添加处理
                    TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
                    tbBizPlaceVo.setTbBizPlace(tbBizPlace);
                    mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
                }*/

                return APIResponse.returnSuccess("订单支付完成！");
            }
            else if(PlaceConstants.ORDER_PAYED_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnSuccess("订单已经支付成功！");
            }
            else{
                logger.warn("订单完成支付异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单完成支付异常！");
            }
        }

        return APIResponse.returnFail("没有该条订单信息！");
    }


    /**
     * 门票支付完成回调操作
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse orderCompleteTicketOperate(ReqOrderOperate reqOrderOperate){
        logger.info("门票支付完成回调---->"+JSON.toJSONString(reqOrderOperate));
            //设置订单状态为已经付款状态
            TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
            tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

            TbBizPlaceOrder record = new TbBizPlaceOrder();
            record.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
            record.setPayStatus(PlaceConstants.PAY_STATUS);
            Date date = new Date();
            record.setOrderStatusChangeDate(date);
            record.setPaymentTime(reqOrderOperate.getPayTime());
            record.setEndTime(date);
            tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample1);

            //馆报名人数加一
            Map<String,Object> map = new HashMap<>();
            map.put("placeId", reqOrderOperate.getPlaceId());
            map.put("addSignupCount", 1);
            placeMapper.updateCount(map);

            TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(reqOrderOperate.getPlaceId());

            TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
            TbBizPlaceOrderItemExample.Criteria placeOrderItem = tbBizPlaceOrderItemExample.createCriteria();
            placeOrderItem.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
            List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
            PlaceTicketPushOrderVo placeTicketPushOrderVo = new PlaceTicketPushOrderVo();

            if(CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
                APIResponse.returnFail("没有该条订单信息！");
            }else{
                List<TicketPushOrderVo> lists = new ArrayList<>();
                for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
                    Integer ticketId = tbBizPlaceOrderItem.getUnitSalePlanId();
                    TbPlaceTicketSalePlan placeTicketSalePlan = tbPlaceTicketSalePlanMapper.selectByPrimaryKey(ticketId);
                    TicketPushOrderVo ticketPush = new TicketPushOrderVo();
                    ticketPush.setTicketName(placeTicketSalePlan.getTicketName());
                    ticketPush.setStartTime(placeTicketSalePlan.getStartTime());
                    ticketPush.setEndTime(placeTicketSalePlan.getEndTime());
                    lists.add(ticketPush);
                }
                placeTicketPushOrderVo.setTicketPushOrderVos(lists);
            }
            TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
            TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
            tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
            List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
            if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                APIResponse.returnFail("没有该条订单信息！");
            }



            TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbPlaceOrder = tbBizPlaceOrderExample.createCriteria();
            tbPlaceOrder.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
            List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
            if(CollectionUtils.isEmpty(tbBizPlaceOrders)){
                APIResponse.returnFail("没有该条订单信息！");
            }

            /**设置服务开关
             * ServiceSwitch 0:不支持，1:支持
             * **/
            TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
            if (parameter != null && parameter.getParameterValue() != null) {
                if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                    OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                    orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                    APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                    if (callBackOrderStatus != null){
                        APIResponse.returnFail("更新订单状态异常");
                    }
                }
            }


            /**加入消息推送，购买门票成功**/
            PlaceMessage placeMessage = new PlaceMessage();
            placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
            placeMessage.setOrderType(4);
            List<Integer> uids = new ArrayList<>();
            uids.add(reqOrderOperate.getUid());
            placeMessage.setUids(uids);

            String salePlanDate =DateUtils.transferDateToString(tbBizPlaceOrderItems.get(0).getConsumeTime());
            String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);

            placeMessage.setDate(salePlanDateNew);
            placeMessage.setPlaceName(tbBizPlace.getName());
            placeMessage.setPlaceId(reqOrderOperate.getPlaceId());

            placeMessage.setPayType(tbBizPlacePayItemList.get(0).getPayType());
            Cagetory cagetory =cagetoryMapper.selectByPrimaryKey(tbBizPlaceOrders.get(0).getCategoryId());
            placeMessage.setCategoryValue(cagetory.getName());
            boolean result = pushMessageOperate(placeMessage);
            //加入消息队列进行异步消息推送处理，场馆系统自己作为生产者也作为消费者。
            if(!result){
                mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
            }
            //insertOrderRecordHistory(reqOrderOperate);
            placeTicketPushOrderVo.setDate(salePlanDateNew);
            placeTicketPushOrderVo.setCategoryId(tbBizPlaceOrders.get(0).getCategoryId());
            /**门票支付完成**/
            orderCallBackHistory(reqOrderOperate);
            commonService.mqSendSportService(reqOrderOperate.getOrderNo(), 1);
            //发送短信
            ticketSmsSendOperate(placeTicketPushOrderVo, reqOrderOperate.getUid(), tbBizPlace);

            return APIResponse.returnSuccess("订单支付完成！");


    }

    /**
     * 订单退款
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse orderUnsubscribeOperate(ReqOrderOperate reqOrderOperate){
    	if(reqOrderOperate.getPlatformType()!=PlatformTypeEnum.BACKSTAGE.getId()){
    		  HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
    	        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
    	        if(userId != null && userId != 0){
    	            reqOrderOperate.setUid(userId);
    	        }
    	}
      
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());
        if (tbBizPlaceOrder==null){
            //包场退款中回调
            String childrenOrderNo = reqOrderOperate.getRefundOrderNo();//退款订单为子订单
            TbBizPlaceOrder childrenOrder = getBizPlaceOrderForBookAll(childrenOrderNo);
            if (childrenOrder == null){
                return APIResponse.returnFail("没有该条订单信息！");
            }
            return placeOrderCallbackService.bookAllOrderUnsubscribeOperate(reqOrderOperate,childrenOrder);
        }
        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单包场回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderCallbackService.billingOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderCallbackService.goodsOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        //商家端门票订单退款
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderCallbackService.ticketOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderCallbackService.shoppingCartOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }

        //设置APP用户一天之内用户退订的次数
        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqOrderOperate.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList =  tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        Map<String, String> placeOrderRuleMap = baseService.getPlaceOrderRule();
        int PLACE_PLAN_MAX_REFUND = 0;
        int PLACE_UNSUBSCRIBE_TIME = 0;
        PLACE_PLAN_MAX_REFUND = Integer.parseInt(placeOrderRuleMap.get("MAX_REFUND_ORDER_NUM"));//一天最大退订次数
        if(CollectionUtils.isEmpty(tbBizPlaceRuleList)){
            PLACE_UNSUBSCRIBE_TIME = PlaceConstants.PLACE_UNSUBSCRIBE_TIME;
            logger.info("订单退款验证规则从默认配置中获取，placeId={}",reqOrderOperate.getPlaceId());
        }
        else {
            TbBizPlaceRule tbBizPlaceRule = tbBizPlaceRuleList.get(0);
            PLACE_UNSUBSCRIBE_TIME = tbBizPlaceRule.getUnsubscribeTime();//提前退订小时数
        }

        if(PlaceConstants.ORDER_OPERATE_APPUSER.equals(reqOrderOperate.getUserType())){

            TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
            tbBizPlaceOrderCriteria.andUidEqualTo(reqOrderOperate.getUid());
            tbBizPlaceOrderCriteria.andOrderStatusChangeDateEqualTo(new Date());
            List<Byte> values = new ArrayList<>();
            values.add(PlaceConstants.ORDER_REFUNDING_STATUS);
            values.add(PlaceConstants.ORDER_REFUND_STATUS);
            tbBizPlaceOrderCriteria.andOrderStatusIn(values);
            tbBizPlaceOrderCriteria.andPayStatusNotEqualTo(PlaceConstants.REFUNDING_EXCEPTION_STATUS);
            List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
            if(CollectionUtils.isNotEmpty(placeOrderList)){
                if (placeOrderList.size() >= PLACE_PLAN_MAX_REFUND) {
                    return APIResponse.returnFail("您一天之内已经退订"+PLACE_PLAN_MAX_REFUND +"次，不能再退订场地！");
                }
            }
        }


        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            if(PlaceConstants.ORDER_PAYED_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){
                //判断退款条件是否成立
                APIResponse apiResponseRefund = isRefund(placeOrderSalePlanList);
                if(apiResponseRefund != null){
                    return apiResponseRefund;
                }
                try {
                    if(PLACE_UNSUBSCRIBE_TIME == 0){
                        return APIResponse.returnFail("本场馆不支持退订");
                    }
                   String startTime = placeOrderSalePlanList.get(0).getStartTime();
                    String startDate = placeOrderSalePlanList.get(0).getDate();
                    Date date = DateUtils.dateStrToDate(startDate + " " + startTime);
                    if(PlaceConstants.ORDER_OPERATE_ADMINUSER.equals(reqOrderOperate.getUserType())){
                        if(System.currentTimeMillis() >= date.getTime()){
                            return APIResponse.returnFail("您已经超过退订时间，不能退订！");
                        }
                    }
                    else {
                        int length = DateUtils.dateDiffHour(new Date(),date);//销售计划日期减去当前日期
                        if(length < PLACE_UNSUBSCRIBE_TIME ){//已经小于开场前24小时，不能退订
                            return APIResponse.returnFail("仅支持开场前" + PLACE_UNSUBSCRIBE_TIME + "小时退订，您已经超过退订时间，不能退订！");
                        }
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }

                APIResponse<RespUserInfoBase> userMsg = null;
                try {
                    userMsg = userServiceFacade.queryUserInfo(reqOrderOperate.getUid());
                    if(!userMsg.isRet()){
                        return APIResponse.returnFail("调用用户系统异常");

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return APIResponse.returnFail("调用用户系统异常");
                }

                RespUserInfoBase respUserInfoBase = userMsg.getData();
                reqOrderOperate.setName(respUserInfoBase.getNickName());

                //TODO 通知订单系统，退款处理，传入旧的的订单号，获取订单系统退款订单号


                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                    return APIResponse.returnFail("不存在订单信息！");
                }


                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    //判断是否为卡支付
                    //与场馆原老板结算的老会员支付方式做特殊处理
                    if(PlaceConstants.PAY_WAY_FOR_CARD.equals(tbBizPlacePayItem.getPayType())
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS.equals(tbBizPlacePayItem.getPayType().toString())){
                        return orderCardPayUnsubscribeOperate(reqOrderOperate,placeOrderSalePlanList);
                    }
                    //判断是否只使用优惠券支付
                    if(PlaceConstants.PAY_WAY_FOR_COUPON.equals(tbBizPlacePayItem.getPayType()) && tbBizPlacePayItemList.size() == 1 ){
                        return APIResponse.returnFail("只使用优惠券支付，不允许退款。");
                    }
                }

                APIRequest<ReqOrderRefund> orderRefundAPIRequest = new APIRequest<>();
                ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
                reqOrderRefund.setSourceBusinessId(Constants.PLACE_BOOKING_CODE);
                reqOrderRefund.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
                reqOrderRefund.setOrderNo(placeOrderSalePlanList.get(0).getOrderNo());
                reqOrderRefund.setReason(reqOrderOperate.getReason());
                reqOrderRefund.setUid(reqOrderOperate.getUid());
                //reqOrderRefund.setRefundNotifyURL(refundUrl);
                reqOrderRefund.setRefundNotifyURL("");
                reqOrderRefund.setNeedAudit(false); //false不需要人工审核.  true: 需要人工审核, 根据业务需求设置
                reqOrderRefund.setOutTradeNo(reqOrderOperate.getOrderNo());
                reqOrderRefund.setOutTradeRefundNo(reqOrderOperate.getOrderNo());//业务系统退款流水号，目前为订单号
                reqOrderRefund.setVer(reqOrderOperate.getVer());
                //查询销售计划表
                List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    ReqRefundProduct refundProduct = new ReqRefundProduct();
                    refundProduct.setPrice(placeOrderSalePlan.getPrice());
                    refundProduct.setProductId(placeOrderSalePlan.getSaleId());
                    refundProduct.setQuantity(1);
                    refundProduct.setProductName(placeOrderSalePlan.getStartTime() + "-" + placeOrderSalePlan.getEndTime()+"时段");
                    reqRefundProducts.add(refundProduct);
                }

                reqOrderRefund.setRefundProductList(reqRefundProducts);


                List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<ReqRefundPayInfo>();
                List<Integer>  payTypeList = PlaceOrderUtil.getPayType();
                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    ReqRefundPayInfo  reqRefundPayInfo = new ReqRefundPayInfo();
                    reqRefundPayInfo.setPayId(tbBizPlacePayItem.getPayType());
                    reqRefundPayInfo.setRefundAmount(tbBizPlacePayItem.getAmount());
                    if(payTypeList.contains(reqRefundPayInfo.getPayId())){
                        reqOrderRefund.setAmount(tbBizPlacePayItem.getAmount());//TODO 累加
                    }

                    reqRefundPayInfoList.add(reqRefundPayInfo);

                }
                reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);
                //区分APP通过larkAppId
                reqOrderRefund.setLarkAppId(reqOrderOperate.getLarkAppId());

                orderRefundAPIRequest.setData(reqOrderRefund);
                APIResponse<RefundStatusEnum> apiResponse = null;
                try {
                    logger.info("申请退款参数："+JSON.toJSONString(reqOrderRefund));
                    apiResponse = this.orderPayService.refundApply(orderRefundAPIRequest);
                } catch (Exception e) {
                    logger.warn("申请退款异常："+e.getMessage());
                    e.printStackTrace();

                }
                if (null == apiResponse){
                    return APIResponse.returnFail("订单退款受理失败，请重试！");
                } else if (!apiResponse.isRet()){
                    logger.warn("订单退款受理失败，orderNo：{}，errMsg：{}",reqOrderOperate.getOrderNo(),apiResponse.getErrmsg());
                    return apiResponse;
                }

                TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
                tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                TbBizPlaceOrder tbBizPlaceRecord = new TbBizPlaceOrder();
                tbBizPlaceRecord.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
                tbBizPlaceRecord.setOrderStatusChangeDate(new Date());

                tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceRecord, tbBizPlaceOrderExample1);

                //释放库存
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                reqPlaceOrderListVo.setUid(null);//清理uid
                reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
                List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    UnitSalePlan unitSalePlan = new UnitSalePlan();
                    unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
                    unitSalePlanIdList.add(unitSalePlan);
                }
                reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
                placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);


                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter1 = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter1 != null && parameter1.getParameterValue() != null) {
                    if (Integer.valueOf(parameter1.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }

                //发送mq消息给运动场业务
                /*PlaceOrderVo placeOrderVo = new PlaceOrderVo();
                placeOrderVo.setUid(reqOrderOperate.getUid());
                placeOrderVo.setPlaceOrderId(reqOrderOperate.getOrderNo());
                placeOrderVo.setType(2);
                mqPlaceProductWrapper.sendOrderInfoToStadium(placeOrderVo);*/

                //TODO 插入退款表

                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                //加入消息推送，提示订场成功
                /*PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(2);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setName(respUserInfoBase.getNickName());
                placeMessage.setCurrTime(DateUtils.transferDateToStringZHCN(new Date()));
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                placeMessage.setServicePhone(parameter.getParameterValue());
                boolean result = pushMessageOperate(placeMessage);*/
                commonService.mqSendSportService(reqOrderOperate.getOrderNo(),2);//sports发消息
                //加入消息推送，app端申请退款推送
                PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(2);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setName(reqOrderOperate.getName());
                placeMessage.setCurrTime(DateUtils.transferDateToStringEN(new Date()));
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                placeMessage.setServicePhone(parameter.getParameterValue());
                boolean result = pushMessageOperate(placeMessage);
                //加入消息队列进行异步消息推送处理
                if(!result){
                    mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
                }
                //封装插入历史记录
                ReqPlaceOrderInfo reqPlaceOrderInfo = new ReqPlaceOrderInfo();
                reqPlaceOrderInfo.setPlaceOrderId(reqOrderOperate.getOrderNo());
                List<ReqPayInfo> reqPayInfos = new ArrayList<>();
                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    ReqPayInfo reqPayInfo = new ReqPayInfo();
                    reqPayInfo.setPayId(tbBizPlacePayItem.getPayType());
                    reqPayInfos.add(reqPayInfo);
                }
                reqPlaceOrderInfo.setPayInfos(reqPayInfos);
                //insertOrderRecordHistory(reqOrderOperate);//1：退款

                return APIResponse.returnSuccess("订单退款受理成功！");
            }
            else if(PlaceConstants.ORDER_REFUNDING_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){
                return APIResponse.returnFail("订单退款已经受理！");
            }
            else {
                logger.warn("订单退款处理异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单退款处理异常！");
            }
        }
        return APIResponse.returnFail("不存在该退款订单！");
    }


    /**
     * 判断是否可以退款
     * @param placeOrderSalePlanList
     * @return
     */
    private APIResponse isRefund(List<PlaceOrderSalePlan> placeOrderSalePlanList){
        //门票不允许退款
        if(placeOrderSalePlanList.get(0).getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return APIResponse.returnFail("门票不允许退款。");
        }

        //达人使用过的订单不允许退款
        if(placeOrderSalePlanList.get(0).getOrderUse() == 2){
            return APIResponse.returnFail("该订单已经使用，不允许退款。");
        }

        //包场订单根据EnableRefund字段判断是否可以退订
        if(placeOrderSalePlanList.get(0).getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)  && placeOrderSalePlanList.get(0).getEnableRefund() == 0){
            return APIResponse.returnFail("该包场订单不允许退款。");
        }

        return null;
    }

    /**
     * 会员卡和优惠券支付 只退会员卡金额 即 订单金额-减优惠券 = 退款金额
     * @param placeOrderId
     * @return
     */
    private TbBizPlacePayItem getPayItem(String placeOrderId){
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        tbBizPlacePayItemCriteria.andPayTypeEqualTo(PlaceConstants.PAY_WAY_FOR_CARD);//会员卡支付
        List<TbBizPlacePayItem> placePayItem = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        if (!org.springframework.util.CollectionUtils.isEmpty(placePayItem)){
            return placePayItem.get(0);
        }
        return null;
    }

    /**
     * 获取订单支付方式
     * @param placeOrderId
     * @return
     */
    private List<TbBizPlacePayItem> placePayItemSize(String placeOrderId){
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlacePayItem> placePayItem = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        if (!org.springframework.util.CollectionUtils.isEmpty(placePayItem)){
            return placePayItem;
        }
        return null;
    }

    /**
     * 会员卡退款处理
     * @param reqOrderOperate
     * @param placeOrderSalePlanList
     * @return
     */

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse orderCardPayUnsubscribeOperate(ReqOrderOperate reqOrderOperate,List<PlaceOrderSalePlan> placeOrderSalePlanList) {
        //根据订单号查询使用的会员卡
        TbBizPlaceMemberOpHistoryExample  tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria tbBizPlaceMemberOpHistoryCriteria = tbBizPlaceMemberOpHistoryExample.createCriteria();
        tbBizPlaceMemberOpHistoryCriteria.andOrderNoEqualTo(reqOrderOperate.getOrderNo());
        List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = tbBizPlaceMemberOpHistoryMapper.selectByExample(tbBizPlaceMemberOpHistoryExample);

        if(CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
            return APIResponse.returnFail("不存在该订单信息！");
        }
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistoryTemp = tbBizPlaceMemberOpHistoryList.get(0);
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getPlaceMemberCardInfo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo(),reqOrderOperate.getPlaceId(),reqOrderOperate.getUid());

        //设置订单状态和支付状态为已经退款状态
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

        TbBizPlaceOrder record = new TbBizPlaceOrder();
        record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
        record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
        Date date = new Date();
        record.setOrderStatusChangeDate(date);
        record.setRefundTime(date);
        record.setEndTime(date);

        List<TbBizPlacePayItem> paySize = placePayItemSize(reqOrderOperate.getOrderNo());
        if (null != paySize && paySize.size() >0){
            //用会员卡支付
            if (paySize.size() == 1){
                record.setCredit(placeOrderSalePlanList.get(0).getDebit());
            }else{
                //用会员卡和优惠券支付 仅退会员卡支付金额
                TbBizPlacePayItem payItem = getPayItem( reqOrderOperate.getOrderNo());
                if (null != payItem){
                    record.setCredit(payItem.getAmount());
                }
            }
        }
        //record.setCredit(placeOrderSalePlanList.get(0).getDebit());
        tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

        //更改订单支付明细的状态为退款状态
        TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        tbBizPlacePayItemCriteria.andPayTypeEqualTo(PlaceConstants.PAY_WAY_FOR_CARD);//会员卡支付
        tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem, tbBizPlacePayItemExample);

        //释放库存
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
        reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
        reqPlaceOrderListVo.setUid(null);//清理uid
        reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
        List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
        for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
            UnitSalePlan unitSalePlan = new UnitSalePlan();
            unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
            unitSalePlanIdList.add(unitSalePlan);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
        placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

        //增加订单金额
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo());
        TbBizPlaceMemberCard tbBizPlaceMemberCardAfter = new TbBizPlaceMemberCard();

        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();

        //如果为储值赠送卡，加上本金金额以及赠送金额
        if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal surplusAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterAmount());
            BigDecimal surplusGiveAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterGiveAmount());
            tbBizPlaceMemberCardAfter.setSurplusAmount(surplusAmount.add(tbBizPlaceMemberCard.getSurplusAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(surplusGiveAmount.add(tbBizPlaceMemberCard.getSurplusGiveAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));

        }
        //如果为储值折扣卡直接加上本金金额
        else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal surplusAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterAmount());
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            tbBizPlaceMemberCardAfter.setSurplusAmount(surplusAmount.add(tbBizPlaceMemberCard.getSurplusAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
        }
        //储值赠送折扣卡处理，加上本金金额以及赠送金额
        else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal surplusAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterAmount());
            BigDecimal surplusGiveAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterGiveAmount());
            tbBizPlaceMemberCardAfter.setSurplusAmount(surplusAmount.add(tbBizPlaceMemberCard.getSurplusAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(surplusGiveAmount.add(tbBizPlaceMemberCard.getSurplusGiveAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));

        }

        placeMemberService.updatePlaceMemberCardInfo(tbBizPlaceMemberCardExample,tbBizPlaceMemberCardAfter);

        //获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqOrderOperate.getUid());
        //获取流水号
        String no = CommonUtils.generateNo(reqOrderOperate.getPlaceId());
        //插入流水记录表
        tbBizPlaceMemberOpHistory.setNo(no);//传入流水号
        tbBizPlaceMemberOpHistory.setOrderNo(orderNo);//存入本次的订单号
        tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList.get(0).getOrderNo());//存入需要退款的订单号
        tbBizPlaceMemberOpHistory.setUid(reqOrderOperate.getUid());
        tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
        tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
        tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo());
        tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard.getCardName());
        tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceMemberOpHistoryTemp.getAmount());
        String opTypeName = tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName();
        tbBizPlaceMemberOpHistory.setOpTypeName(opTypeName + "退款");
        tbBizPlaceMemberOpHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
        tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCardAfter.getSurplusAmount());
        tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCardAfter.getSurplusGiveAmount());
        tbBizPlaceMemberOpHistory.setPlaceId(reqOrderOperate.getPlaceId());
        tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
        tbBizPlaceMemberOpHistory.setSourceType(tbBizPlaceMemberOpHistoryList.get(0).getSourceType());
        tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        tbBizPlaceMemberOpHistory.setOpBeforeNumbers(0);
        tbBizPlaceMemberOpHistory.setOpAfterNumbers(0);
        tbBizPlaceMemberOpHistory.setMemo("会员卡退款");
        tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
        tbBizPlaceMemberOpHistory.setCreateUid(reqOrderOperate.getUid());
        tbBizPlaceMemberOpHistory.setPayType(PlaceConstants.PAY_WAY_FOR_CARD);
        tbBizPlaceMemberOpHistory.setPlatform(reqOrderOperate.getPlatformType());
        tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);

        //场馆报名人数减一
        Map<String,Object> map = new HashMap<>();
        map.put("placeId", placeOrderSalePlanList.get(0).getPlaceId());
        map.put("subtractSignupCount", 1);
        placeMapper.updateCount(map);

        TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());
        /*try {
            this.searchService.addPlaceIndex(tbBizPlace, null);
        } catch (Exception e) {
            logger.error("增加索引失败，加入消息队列进行处理!");
            //加入消息队列进行异步处理
            TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
            tbBizPlaceVo.setTbBizPlace(tbBizPlace);
            mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
        }*/

        //加入消息推送，提示订场成功
        PlaceMessage placeMessage = new PlaceMessage();
        placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
        placeMessage.setOrderType(2);
        List<Integer> uids = new ArrayList<>();
        uids.add(reqOrderOperate.getUid());
        placeMessage.setUids(uids);
        String salePlanDate = placeOrderSalePlanList.get(0).getDate();
        String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
        placeMessage.setDate(salePlanDateNew);
        placeMessage.setPlaceName(tbBizPlace.getName());
        placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
        placeMessage.setName(reqOrderOperate.getName());
        placeMessage.setCurrTime(DateUtils.transferDateToStringZHCN(new Date()));
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
        placeMessage.setServicePhone(parameter.getParameterValue());
        boolean result = pushMessageOperate(placeMessage);
        //加入消息队列进行异步消息推送处理
        if(!result){
            mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
        }
        commonService.mqSendSportService(reqOrderOperate.getOrderNo(),2);

        //退款发送短信
        smsRefundSendOperate(placeOrderSalePlanList,reqOrderOperate.getUid(),tbBizPlace);
        /**会员卡退款**/
        orderCallBackHistory(reqOrderOperate);

        return APIResponse.returnSuccess("订单退款成功！");

    }


    /**
     * 如果支付系统完成退款，消息队列订阅到，进行订单处理
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCompleteUnsubscribeOperate(ReqOrderOperate reqOrderOperate) {
        //需要进行权限控制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");
        }
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());

        if (tbBizPlaceOrder==null){
            String childrenOrderNo = reqOrderOperate.getRefundOrderNo();//退款订单为子订单
            TbBizPlaceOrder childrenOrder = getBizPlaceOrderForBookAll(childrenOrderNo);
            if (childrenOrder == null){
                return APIResponse.returnFail("没有该条订单信息！");
            }
            //包场退款完成回调
            return placeOrderCallbackService.bookAllOrderCompleteUnsubscribeOperate(reqOrderOperate,childrenOrder);
        }

        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCompleteUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderCallbackService.billingOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderCallbackService.goodsOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        //商家端对线上门票订单退款
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderCallbackService.ticketOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderCallbackService.shoppingCartOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        
        
        
        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {
            if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                TbBizPlaceOrder record = new TbBizPlaceOrder();
                //设置支付状态
                if (reqOrderOperate.getExceptionFlag()){
                    record.setPayStatus(PlaceConstants.REFUNDING_EXCEPTION_STATUS);
                }
                else {
                    record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
                }

                //设置订单状态和支付状态为已经退款状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
                Date date = new Date();
                record.setOrderStatusChangeDate(date);
                record.setRefundTime(date);
                record.setEndTime(date);
                record.setCredit(placeOrderSalePlanList.get(0).getDebit());
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);
                commonService.mqSendSportService(reqOrderOperate.getOrderNo(),2);


                //更改订单支付明细的状态为退款状态
                TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem, tbBizPlacePayItemExample);

                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter != null && parameter.getParameterValue() != null) {
                    if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }

                //场馆报名人数减一
                Map<String,Object> map = new HashMap<>();
                map.put("placeId", placeOrderSalePlanList.get(0).getPlaceId());
                map.put("subtractSignupCount", 1);
                placeMapper.updateCount(map);

                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());
                /*try {
                    this.searchService.addPlaceIndex(tbBizPlace, null);
                } catch (Exception e) {
                    logger.error("增加索引失败，加入消息队列进行处理!");
                    //加入消息队列进行异步处理
                    TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
                    tbBizPlaceVo.setTbBizPlace(tbBizPlace);
                    mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
                }*/
                /**商家端退款**/
                orderCallBackHistory(reqOrderOperate);
                //发送退款短信
                smsRefundSendOperate(placeOrderSalePlanList, reqOrderOperate.getUid(),tbBizPlace);

                //释放场地状态更新场地价格
                try {
                    placeInnerService.syncSalePlanPriceForRefundOrder(reqOrderOperate.getOrderNo());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return APIResponse.returnSuccess("订单退款成功！");
            } else if (PlaceConstants.ORDER_REFUND_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnSuccess("订单退款已经成功！");
            }
            else {
                logger.warn("订单退款异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单退款异常！");
            }

        }

        return APIResponse.returnFail("不存在该退款订单！");

    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCancleToUnsubscribeOperate(ReqOrderOperate reqOrderOperate) {
        //需要进行权限控制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());

        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());
        if(tbBizPlaceOrder == null){
            String childrenOrderNo = reqOrderOperate.getRefundOrderNo();//退款订单为子订单
            TbBizPlaceOrder childrenOrder = getBizPlaceOrderForBookAll(childrenOrderNo);
            if (childrenOrder == null){
                return APIResponse.returnFail("没有该条订单信息！");
            }
            //包场退款异常回调
            return placeOrderCallbackService.bookAllOrderCancleToUnsubscribeOperate(reqOrderOperate,childrenOrder);
        }
        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCancleToUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderCallbackService.billingOrderCancleToUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderCallbackService.goodsOrderCancleToUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderCallbackService.shoppingCartOrderCancleToUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if (CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {
            if (PlaceConstants.ORDER_CLOSE_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                /*//设置订单状态和支付状态为已经退款状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                TbBizPlaceOrder record = new TbBizPlaceOrder();
                record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
                record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
                Date date = new Date();
                record.setOrderStatusChangeDate(date);
                record.setRefundTime(date);
                record.setEndTime(date);
                record.setDebit(new BigDecimal(0));
                record.setCredit(placeOrderSalePlanList.get(0).getDebit());
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

                //更改订单支付明细的状态为退款状态
                TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,tbBizPlacePayItemExample);*/

                //设置退款中状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
                tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                TbBizPlaceOrder tbBizPlaceRecord = new TbBizPlaceOrder();
                tbBizPlaceRecord.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
                tbBizPlaceRecord.setOrderStatusChangeDate(new Date());

                tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceRecord, tbBizPlaceOrderExample1);

                List<Integer> values = new ArrayList<>();
                values.add(PlaceConstants.PAY_WAY_ALIPAY);
                values.add(PlaceConstants.PAY_WAY_WEICHAT);
                values.add(PlaceConstants.PAY_WAY_WEICHATH5);
                values.add(PlaceConstants.PAY_WAY_UNION_PAY);
                values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
                values.add(PlaceConstants.PAY_WAY_FOR_WEB_ALIPAY);
                values.add(PlaceConstants.PAY_WAY_FOR_WEIXIN_APPLET);
                values.add(PlaceConstants.PAY_WAY_FOR_UNION_POS_PAY);//增加pos
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemCriteria.andPayTypeIn(values);
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                    APIResponse.returnFail("没有该条订单信息！");
                }

                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter != null && parameter.getParameterValue() != null) {
                    if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }


                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                //加入消息推送，提示订场成功
                PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(3);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setPayType(tbBizPlacePayItemList.get(0).getPayType());
                boolean result = pushMessageOperate(placeMessage);
                //异常时加入消息队列进行异步消息推送处理
                if(!result){
                    mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
                }

                //TODO 发送短息

                return APIResponse.returnSuccess("订单退款受理成功！");

            }
            else if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnFail("订单退款已经受理！");
            }
            else {
                logger.warn("订单退款异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单退款异常！");
            }
        }
        return APIResponse.returnFail("不存在该退款订单！");
    }


    @Override
    public APIResponse<RespPayInfoList> getPayInfo(ReqGetPayInfo reqGetPayInfo) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        reqGetPayInfo.setUid(userId);
        RespPayInfoList respPayInfoList = new RespPayInfoList();
        //获取支付信息
        ReqSysPayInfo reqSysPayInfo = new ReqSysPayInfo();
        reqSysPayInfo.setSourceSystemId(PlaceConstants.PLACE_SYSTEM_CODE);
        reqSysPayInfo.setSourceBusinessId(PlaceConstants.BUSINESS_CODE_PAYINFO_PREFIX + reqGetPayInfo.getPayInfoType());
        APIResponse<List<com.quanyan.orderpay.response.RespPayInfo>> listAPIResponse = this.orderPayService.selectEnablePayInfos(reqSysPayInfo);
        if(CollectionUtils.isEmpty(listAPIResponse.getData())){
            ReqSysPayInfo reqSysPayInfoReg = new ReqSysPayInfo();
            List<Integer> ids = new ArrayList<>();
            switch (reqGetPayInfo.getPayInfoType()){
                case 0:
                    ids.add(1);
                    ids.add(2);
                    break;
                default:
                    ids.add(reqGetPayInfo.getPayInfoType());break;
            }

            //初始化
            reqSysPayInfoReg.setPayIds(ids);
            reqSysPayInfoReg.setSourceSystemId(PlaceConstants.PLACE_SYSTEM_CODE);
            reqSysPayInfoReg.setSourceBusinessId(PlaceConstants.BUSINESS_CODE_PAYINFO_PREFIX + reqGetPayInfo.getPayInfoType());
            this.orderPayService.applyEnablePayInfos(reqSysPayInfoReg);

            //再次查询
            ReqSysPayInfo reqSysPayInfoRetry = new ReqSysPayInfo();
            reqSysPayInfoRetry.setSourceSystemId(PlaceConstants.PLACE_SYSTEM_CODE);
            reqSysPayInfoRetry.setSourceBusinessId(PlaceConstants.BUSINESS_CODE_PAYINFO_PREFIX + reqGetPayInfo.getPayInfoType());
            listAPIResponse = this.orderPayService.selectEnablePayInfos(reqSysPayInfoRetry);
        }
        respPayInfoList.setPayInfos(listAPIResponse.getData());

        //TODO 获取鸟蛋可用信息，目前不需要获取
        /*TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqGetPayInfo.getOrderNo());
        tbBizPlaceOrderCriteria.andUidEqualTo(reqGetPayInfo.getUid());
        List<TbBizPlaceOrder> tbBizPlaceOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if(CollectionUtils.isEmpty(tbBizPlaceOrderList)){
            return APIResponse.returnFail("不存在该订单信息！");
        }
        TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrderList.get(0);
        com.quanyan.api.APIRequest<ReqRuleDetail> apiRequest = new  com.quanyan.api.APIRequest<>();
        ReqRuleDetail reqRuleDetail = new ReqRuleDetail();
        reqRuleDetail.setUid(reqGetPayInfo.getUid());
        reqRuleDetail.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqRuleDetail.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqRuleDetail.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
        reqRuleDetail.setOrderAmount(tbBizPlaceOrder.getDebit());
        apiRequest.setData(reqRuleDetail);
        APIResponse<List<RespRuleDetail>>  respRuleDetailAPIResponse = userAssetsService.getUserAccumulateAndRule(apiRequest);
        if(respRuleDetailAPIResponse == null || !respRuleDetailAPIResponse.isRet()){
            return APIResponse.returnFail("调用资产系统异常！");
        }
        List<RespRuleDetail> respRuleDetailList = respRuleDetailAPIResponse.getData();
        if(CollectionUtils.isNotEmpty(respRuleDetailList)){
            RespRuleDetail respRuleDetail = respRuleDetailList.get(0);
            List<RespAccumulateRule> accumulateRuleList = new ArrayList<>();
            RespAccumulateRule respAccumulateRule = new RespAccumulateRule();
            respAccumulateRule.setAmount(respRuleDetail.getExchangeRMB());
            respAccumulateRule.setPayId(PlaceConstants.PAY_WAY_FOR_AGES);
            respAccumulateRule.setName("鸟蛋抵扣");
            respAccumulateRule.setDescribe(respRuleDetail.getUseAccumulate() + "可抵扣￥" + respRuleDetail.getExchangeRMB());
            accumulateRuleList.add(respAccumulateRule);
            respPayInfoList.setAccumulateRuleList(accumulateRuleList);
        }
        else {
            RespRuleDetail respRuleDetail = respRuleDetailList.get(0);
            List<RespAccumulateRule> accumulateRuleList = new ArrayList<>();
            RespAccumulateRule respAccumulateRule = new RespAccumulateRule();
            respAccumulateRule.setAmount(new BigDecimal(0));
            respAccumulateRule.setPayId(PlaceConstants.PAY_WAY_FOR_AGES);
            respAccumulateRule.setName("鸟蛋抵扣");
            respAccumulateRule.setDescribe("0可抵扣￥0");
            accumulateRuleList.add(respAccumulateRule);
            respPayInfoList.setAccumulateRuleList(accumulateRuleList);
        }*/

        return APIResponse.returnSuccess(respPayInfoList);
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    @Override
    public APIResponse<RespPreOrder> orderPay(ReqOrderPay reqOrderPay) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        String ver = httpServletRequest.getHeader("APPVersion");
        reqOrderPay.setUid(userId);
        //校验是否存在该订单信息，是否超过下单时间
        if (reqOrderPay.getUseType() != null && reqOrderPay.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            //如果购买门票，走购买门票逻辑
            return apiPlaceTicketService.ticketOrderPay(reqOrderPay);

        }
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderPay.getOrderNo());
        queryMap.put("uid", reqOrderPay.getUid());

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {
            Date orderDate = placeOrderSalePlanList.get(0).getOrderTime();
            long orderTime = orderDate.getTime();
            if(System.currentTimeMillis() - orderTime >= PlaceConstants.ORDER_EXPIRED_TIME){
                return APIResponse.returnFail("下单时间超过十分钟，您已经不能支付！");
            }
            if (PlaceConstants.ORDER_PREPAY_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {

                TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderPay.getOrderNo());
                tbBizPlaceOrderCriteria.andUidEqualTo(reqOrderPay.getUid());
                List<TbBizPlaceOrder> tbBizPlaceOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
                TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrderList.get(0);
                tbBizPlaceOrder.setPlatform(reqOrderPay.getPlatformType());
                tbBizPlaceOrderMapper.updateByPrimaryKeySelective(tbBizPlaceOrder);
                ReqPlaceOrderInfo reqPlaceOrderInfo = new ReqPlaceOrderInfo();
                RespPlaceUserInfo userInfo = new RespPlaceUserInfo();
                reqPlaceOrderInfo.setUserInfo(userInfo);
                userInfo.setUid(tbBizPlaceOrder.getUid());
                userInfo.setMobile(tbBizPlaceOrder.getMobile());
                userInfo.setNickName(tbBizPlaceOrder.getCustomerName());

                reqPlaceOrderInfo.setOrderAmount(tbBizPlaceOrder.getDebit());
                reqPlaceOrderInfo.setUid(tbBizPlaceOrder.getUid());
                reqPlaceOrderInfo.setCityId(reqOrderPay.getMchId());
                reqPlaceOrderInfo.setOrderNo(reqOrderPay.getOrderNo());
                reqPlaceOrderInfo.setSubjectURL(tbBizPlace.getBizPlaceUrl());
                reqPlaceOrderInfo.setOpenId(reqOrderPay.getOpenId());
                reqPlaceOrderInfo.setAPPVersion(ver);
                reqPlaceOrderInfo.setMchId(reqOrderPay.getMchId());
                reqPlaceOrderInfo.setLarkAppId(reqOrderPay.getLarkAppId());

                //reqPlaceOrderInfo.setPayInfos(reqOrderPay.getPayInfos());

                List<Integer> saleIdList = new ArrayList<>();


                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    saleIdList.add(placeOrderSalePlan.getUnitSalePlanId());
                }
                TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
                TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria = tbBizPlaceUnitSalePlanExample.createCriteria();
                tbBizPlaceUnitSalePlanCriteria.andIdIn(saleIdList);
                List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);

                //TODO 用户使用非虚拟币的支付方式列表，（只能使用一种，不能混合使用，例如不能同时使用支付宝支付和微信支付）
                List<Integer> values = new ArrayList<>();
                values.add(PlaceConstants.PAY_WAY_ALIPAY);
                values.add(PlaceConstants.PAY_WAY_WEICHAT);
                values.add(PlaceConstants.PAY_WAY_WEICHATH5);
                values.add(PlaceConstants.PAY_WAY_UNION_PAY);
                values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
                values.add(PlaceConstants.PAY_WAY_FOR_WEB_ALIPAY);
                values.add(PlaceConstants.PAY_WAY_FOR_WEIXIN_APPLET);


                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderPay.getOrderNo());
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                List<ReqPayInfo> payInfosTemp = reqOrderPay.getPayInfos();//获取当前用户使用的支付方式
                List<ReqPayInfo> payInfos = new ArrayList<>();
                for (ReqPayInfo reqPayInfo : payInfosTemp) {//查找非鸟蛋支付、优惠券支付的payId
                    if(values.contains(reqPayInfo.getPayId())){
                        payInfos.add(reqPayInfo);
                    }
                }

                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    if(values.contains(tbBizPlacePayItem.getPayType())){
                        for (ReqPayInfo payInfo : payInfos) {
                            if(!tbBizPlacePayItem.getPayType().equals(payInfo.getPayId())){
                                //说明用户使用的支付方式发生改变，需要更新数据库，更新tbBizPlacePayItem的payType
                                tbBizPlacePayItem.setPayType(payInfo.getPayId());
                                TbBizPlacePayItem newTbBizPlacePayItem = new TbBizPlacePayItem();
                                newTbBizPlacePayItem.setId(tbBizPlacePayItem.getId());
                                newTbBizPlacePayItem.setPayType(payInfo.getPayId());
                                tbBizPlacePayItemMapper.updateByPrimaryKeySelective(newTbBizPlacePayItem);
                            }
                        }
                    }
                }

                List<ReqPayInfo> payNewInfos = new ArrayList<>();
                List<ReqPayInfo> payInfoList =
                        tbBizPlaceOrderManagerMapper.selectPayTypeGroupByPayTypeAndOrderId(tbBizPlaceOrder.getPlaceOrderId());
                for (ReqPayInfo reqPayInfo : payInfoList) {
                    //优惠券支付需要以下信息
                    if(PlaceConstants.PAY_WAY_FOR_COUPON == reqPayInfo.getPayId()){
                        reqPayInfo.setSubjectCode(reqPayInfo.getSubjectCode());
                    }
                    reqPayInfo.setCityId(tbBizPlace.getCityId());
                    reqPayInfo.setPlaceId(reqPlaceOrderInfo.getPlaceId());
                    reqPayInfo.setOrderType(CouponOrderType.PLACE_TICKETS.getId().byteValue());
                    reqPayInfo.setSportType(placeOrderSalePlanList.get(0).getCategoryId().byteValue());
                    payNewInfos.add(reqPayInfo);
                }
                /*for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    ReqPayInfo reqPayInfo = new ReqPayInfo();
                    reqPayInfo.setAmount(tbBizPlacePayItem.getAmount());
                    reqPayInfo.setPayId(tbBizPlacePayItem.getPayType());
                    //优惠券支付需要以下信息
                    if(PlaceConstants.PAY_WAY_FOR_COUPON.equals(tbBizPlacePayItem.getPayType())){
                        reqPayInfo.setSportType(placeOrderSalePlanList.get(0).getCategoryId().byteValue());
                        reqPayInfo.setSubjectCode(tbBizPlacePayItem.getSubjectCode());
                        reqPayInfo.setOrderType(CouponOrderType.PLACE.getId().byteValue());
                        reqPayInfo.setPlaceId(reqPlaceOrderInfo.getPlaceId());
                    }
                    payNewInfos.add(reqPayInfo);
                }*/

                reqPlaceOrderInfo.setPayInfos(payNewInfos);

                //设置回调方式
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_ORDER_CALLBACK_TYPE.getCode());
                Integer callbackType = 0;
                if (parameter != null && parameter.getParameterValue() != null){
                    callbackType = Integer.valueOf(parameter.getParameterValue());
                }
                reqPlaceOrderInfo.setCallbackType(callbackType);
                reqPlaceOrderInfo.setPlatformType(reqOrderPay.getPlatformType());
                if (!org.springframework.util.StringUtils.isEmpty(reqOrderPay.getReturnUrlForH5())){
                    reqPlaceOrderInfo.setReturnUrlForH5(reqOrderPay.getReturnUrlForH5());
                }
                if (!org.springframework.util.StringUtils.isEmpty(reqOrderPay.getShowURLForH5())){
                    reqPlaceOrderInfo.setShowURLForH5(reqOrderPay.getShowURLForH5());
                }
                //调用订单系统，获取预支付信息
                APIResponse<RespPreOrder> respPreOrderAPIResponse = null;
                try {
                    respPreOrderAPIResponse = noticeOrderSystem(reqPlaceOrderInfo,tbBizPlace,tbBizPlaceUnitSalePlanList,false);
                    logger.info("respPreOrderAPIResponse------>"+JSON.toJSONString(respPreOrderAPIResponse));
                    if(respPreOrderAPIResponse == null || !respPreOrderAPIResponse.isRet()){
                        throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
                    }

                }
                catch (Exception e){
                    if(respPreOrderAPIResponse != null && !respPreOrderAPIResponse.isRet()){
                        logger.warn("uid：{} ，error：{} " ,reqPlaceOrderInfo.getUid(),respPreOrderAPIResponse.getErrmsg());
                    }
                    else {
                        logger.warn("uid：{} ，error：{} " ,reqPlaceOrderInfo.getUid(),e.getMessage());
                    }
                    if (respPreOrderAPIResponse.getErrcode() == 21012){
                        throw new BizException(PlaceErrorCodeEnum.TICKET_PAY_CONFIG_ERROR);
                    }

                    if ("该优惠券不能使用".equals(respPreOrderAPIResponse.getErrmsg())){
                        throw new BizException(PlaceErrorCodeEnum.COUPON_NOT_USE);
                    }

                    throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
                }

                return respPreOrderAPIResponse;
            }
            else if (PlaceConstants.ORDER_PAYED_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnFail("该订单已经支付！");
            }
            else {
                return APIResponse.returnFail("订单支付异常！");
            }
        }
        return APIResponse.returnFail("不存在该订单信息！");
    }

    @Override
    public APIResponse<RespOrderShare> orderShare(ReqOrderShare reqOrderShare) {
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        reqOrderShare.setUid(userId);
        RespOrderShare respOrderShare = new RespOrderShare();
        //通过订单号获取场馆信息
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderShare.getOrderNo());
        List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if (CollectionUtils.isEmpty(placeOrderList)){
            return APIResponse.returnFail("不存在该分享信息！");
        }

        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeOrderList.get(0).getPlaceId());
        respOrderShare.setTitle(tbBizPlace.getName());
        respOrderShare.setContent(tbBizPlace.getAddress());
        respOrderShare.setImageUrl(tbBizPlace.getBizPlaceUrl());
        //获取分享的url，包含用户信息
        APIResponse<RespUserInfoBase> result = userServiceFacade.queryUserInfo(placeOrderList.get(0).getUid());
        if(!result.isRet()){
            return APIResponse.returnFail("不存在该用户！");
        }
        String nickName = result.getData().getNickName();
        String icon = result.getData().getIcon();

        String userToken = (String)placeRedisTemplate.get(PlaceConstants.USER_SHARE_PREFIX + userId);
        if(userToken == null){
            userToken = UUIDUtils.getUUID();
            placeRedisTemplate.set(PlaceConstants.USER_SHARE_PREFIX + userId, userToken,Constants.SHARE_TOKEN_EXPIRED_TIME);
            placeRedisTemplate.set(userToken, userId,Constants.SHARE_TOKEN_EXPIRED_TIME);
        }
        respOrderShare.setShareUrl((placeShareUrl + "?token=" + userToken + "&nickName=" + nickName + "&icon=" + icon));
        //如果用户为俱乐部管理员，获取俱乐部id
        respOrderShare.setIsSportClubAdmin(0);
        List<Integer> clubids = null;
        try {
            clubids = clubOpenService.getSportClubIdsOfAdmin(userId, placeOrderList.get(0).getCategoryId());
        } catch (Exception e) {
            logger.warn("调用俱乐部系统，获取俱乐部id异常：{}" , e.getMessage());
        }
        if(CollectionUtils.isNotEmpty(clubids)){
            respOrderShare.setIsSportClubAdmin(1);
            respOrderShare.setClubId(clubids.get(0));
            respOrderShare.setCategoryId(placeOrderList.get(0).getCategoryId());
        }

        return APIResponse.returnSuccess(respOrderShare);
    }

    @Override
    public APIResponse<RespInviteUser> inviteUser(ReqInviteUser reqInviteUser) {
        Integer uid = 0;
        String mobile = null;
        try {
            uid = (Integer)placeRedisTemplate.get(reqInviteUser.getToken());
            if(uid == null || uid == 0){
                uid = userServiceFacade.getUserIdByToken(reqInviteUser.getToken());//兼容之前以cookie作为token的请求
            }
            if(uid == null || uid == 0){
                return APIResponse.returnFail("该邀请信息已经失效，请重新发起邀请！");
            }

            APIResponse<RespUserInfoBase> result = userServiceFacade.queryUserInfo(uid);
            if(!result.isRet()){
                return APIResponse.returnFail("不存在该用户发起的邀请！");
            }
            mobile = result.getData().getMobile();
        } catch (Exception e) {
            logger.warn("调用用户中心异常：{}", e.getMessage());
            return APIResponse.returnFail("系统异常！");
        }

        /*TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqInviteUser.getOrderNo());
        List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if (CollectionUtils.isEmpty(placeOrderList)){
            return APIResponse.returnFail("不存在该邀请信息！");
        }
        RespInviteUser respInviteUser = new RespInviteUser();
        respInviteUser.setPlaceId(placeOrderList.get(0).getPlaceId());
        respInviteUser.setCategoryId(placeOrderList.get(0).getCategoryId());
        respInviteUser.setStartDate(System.currentTimeMillis());
        respInviteUser.setEndDate(System.currentTimeMillis());
        respInviteUser.setIsAutoCompleteSalePlan(Constants.YES);
        respInviteUser.setIsNeedUserInfo(Constants.NO);*/

        RespInviteUser respInviteUser = new RespInviteUser();
        //调用任务中心邀请好友接口，判断用户类型
        ReqUserInvite reqUserInvite = new ReqUserInvite(uid,mobile,reqInviteUser.getMobile());
        RespUserInvite respUserInvite = null;
        try {
           // respUserInvite = userInviteServiceFacade.isNewUser(reqUserInvite);
            respUserInvite = new RespUserInvite();
            respUserInvite.setStatus(Constants.RespUserInviteStatus.INVITE);
            if(respUserInvite != null){
                if(Constants.RespUserInviteStatus.INVITE == respUserInvite.getStatus().byteValue()){
                    //respInviteUser.setDesc(respUserInvite.getEggNum() + "鸟蛋已存入手机号" + reqInviteUser.getMobile());
                    respInviteUser.setDesc("您已成功加入百灵鸟，下载APP体验吧!");
                }
                else if(Constants.RespUserInviteStatus.REGISTER_ED == respUserInvite.getStatus().byteValue()){
                    respInviteUser.setDesc("你已经是百灵鸟用户");
                }
                else if(Constants.RespUserInviteStatus.INVITE_ED == respUserInvite.getStatus().byteValue()){
                    respInviteUser.setDesc("你已经被邀请过了");
                }
            }
        } catch (Exception e) {
            logger.warn("调用任务中心邀请好友接口异常：{}" , e.getMessage());
            return APIResponse.returnFail("系统异常");
        }

        return APIResponse.returnSuccess(respInviteUser);
    }

    /**
     * 消息推送
     * @param placeMessage
     * @return
     */
    private boolean pushMessageOperate(PlaceMessage placeMessage) {
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.ORDER.value() + System.currentTimeMillis());
        pushMessage.setTo(placeMessage.getUids());                          //下单用户的uid
        pushMessage.setLogo(Constants.LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        String body = "";
        String title = "";
        String payType = "";
        NewBody newBody = null;
        /**orderType:1 App订场，2 App退款 4: 购买门票**/
        if(placeMessage.getOrderType() == 1){
            title = "场地预订提醒";
            body = "您已成功预订" + placeMessage.getDate() + placeMessage.getPlaceName() + "的" +placeMessage.getCategoryValue()+ "场地。";
        }
        else if(placeMessage.getOrderType() == 2){
            //title = "尊敬的" +placeMessage.getName()+"，您于" +placeMessage.getCurrTime() + "申请"+ placeMessage.getPlaceName() + "退订业务已成功，退款将于三个工作日内返还。有疑问请致电" + placeMessage.getServicePhone();
            title = "场地退款提醒";
            newBody = getNewBody(placeMessage);
            payload.setNewBody(newBody);
        }
        else if(placeMessage.getOrderType() == 3){

            if(placeMessage.getPayType() == 1){
                payType = "支付宝";
            }
            else if(placeMessage.getPayType() == 2 || placeMessage.getPayType() == 3){
                payType = "微信";
            }
            body="很抱歉，您的订单支付异常，系统将在2个工作日内退回已支付款项，具体到账时间以" +payType + "处理为准。如有需要，可重新下单。";
        }
        if(placeMessage.getOrderType() == 4){
            title = "场地门票购买提醒";
            int count = placeTicketService.getTicketSaleCountByOrderNo(placeMessage.getOrderNo());
            body = "您已成功购买" + placeMessage.getDate() + placeMessage.getPlaceName() + "的" +placeMessage.getCategoryValue()+ "门票"+ count +"张。";
        }
        if (placeMessage.getOrderType() == 2){//app端退款
            payload.setMsgType(MsgType.ORDER_MSG.value());//订单 5
        }else{
            payload.setMsgType(MsgType.JUMP_MSG.value());
        }

        Alert alert = new Alert();
        alert.setTitle("场馆订单");
        pushMessage.setAlert(alert);
        alert.setBody(title);
        payload.setTitle(title);
        payload.setBody(body);
        payload.setBoxType(BoxType.PLACE_ORDER_MSG.value());
        payload.setUrl("/api/place/shops/orderDetail");
        Jump jump = new Jump();
        jump.setIdType(IdType.PLACE_ORDER_DETAIL_PAGE.value());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("orderNo",placeMessage.getOrderNo());
        jump.setParam(param);
        payload.setJump(jump);
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        try {
            String postJson = JSON.toJSONString(reqPushMessage);
            logger.info("---------推送消息：" + postJson);
            String result = HttpClientUtils.postJson(cAddress + "/push/NewMsg.api", postJson);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errcode = jsonObject.getString("errcode");
            logger.info("---------推送返回：" + result);
            if(errcode != null && errcode.equals("200")){
                return true;
            }
        } catch (Exception e) {
            logger.info("推送消息失败，" + e.getMessage());
        }
        return false;

    }


    private NewBody getNewBody(PlaceMessage placeMessage){
        NewBody newBody = new NewBody();
        newBody.setB("");
        newBody.setbColor("");

        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add(placeMessage.getOrderNo());
        map.put("placeOrderId",list);
        BigDecimal payAmount = financeCommonManagerMapper.getOrderDiscountAmount(map);
        List<Entry> entries = new ArrayList<>();
        Entry entry = new Entry();
        entry.setKey("退款金额");
        entry.setValue(payAmount.toString()+"元");
        entry.setKcolor("#ed4d4d");
        entry.setVcolor("#ed4d4d");
        entries.add(entry);

        Entry entry1 = new Entry();
        entry1.setKey("场馆名称");
        entry1.setValue(placeMessage.getPlaceName());
        entry1.setKcolor("");
        entry1.setVcolor("");
        entries.add(entry1);

        Entry entry2 = new Entry();
        entry2.setKey("申请时间");
        entry2.setValue(DateUtils.transferLongToDateStrings(System.currentTimeMillis()));
        entry2.setKcolor("");
        entry2.setVcolor("");
        entries.add(entry2);

        Entry entry3 = new Entry();
        entry3.setKey("到账时间");
        entry3.setValue("三个工作日内");
        entry3.setKcolor("");
        entry3.setVcolor("");
        entries.add(entry3);

        newBody.setEntries(entries);
       return newBody;
    }
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    @Override
    public APIResponse<RespPreOrder> cardPay(ReqPlaceOrderInfo reqPlaceOrderInfo) {
        //用户验证
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        reqPlaceOrderInfo.setUid(userId);
        reqPlaceOrderInfo.setItemUuid(UUIDUtils.createId());
        APIResponse apiResponse = null;

        apiResponse = payUserVerification(reqPlaceOrderInfo);
        if( apiResponse != null){
            return apiResponse;
        }
        //下单验证
        apiResponse = orderVerification(reqPlaceOrderInfo);
        if( apiResponse != null && !apiResponse.isRet()){
            return apiResponse;
        }
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(reqPlaceOrderInfo.getPlaceId());
        reqPlaceOrderInfo.setCityId(tbBizPlace.getCityId());

        List<ReqPayInfo> payInfos = reqPlaceOrderInfo.getPayInfos();
        RespCoupon respCoupon = null;
        boolean result = false;
        Iterator<ReqPayInfo> it = payInfos.iterator();
        while (it.hasNext()) {
            ReqPayInfo payInfo = it.next();
            if (PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfo.getPayId())) {
                /**兼容老版本，优惠券折扣时，提示升级最新版本**/
                BigDecimal amount = payInfo.getAmount();
                if (null != amount && 0 == amount.compareTo(BigDecimal.ZERO)){
                    return APIResponse.returnFail(PlaceErrorCodeEnum.COUPON_DISCOUNT_PAY_ERROR);
                }
                payInfo.setSportType(reqPlaceOrderInfo.getCategoryId().byteValue());
                payInfo.setOrderType(CouponOrderType.PLACE.getId().byteValue());
                payInfo.setPlaceId(reqPlaceOrderInfo.getPlaceId());
                payInfo.setCityId(reqPlaceOrderInfo.getCityId());
                //获取优惠卷
                try {
               	 APIResponse<RespCoupon>  apiCouponResponse = couponService.getInfoByCode(payInfo.getSubjectCode());
                   if(apiCouponResponse.isRet()){
                       respCoupon = apiCouponResponse.getData();
                   }else {
                       logger.info("获取优惠券信息失败：" + apiCouponResponse.getErrmsg());
                       throw new BizException(PlaceErrorCodeEnum.COUPON_SYSTEM_ERROR);
                   }
               } catch (Exception e) {
                   e.printStackTrace();
                   throw new BizException(PlaceErrorCodeEnum.COUPON_SYSTEM_ERROR);
               }
                result = true;
            }
        }

        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
        reqPlaceOrderListVo.setUnitSalePlanIdList(reqPlaceOrderInfo.getUnitSalePlanIdList());
        reqPlaceOrderListVo.setUid(reqPlaceOrderInfo.getUid());
        reqPlaceOrderListVo.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        reqPlaceOrderListVo.setCategoryId(reqPlaceOrderInfo.getCategoryId());
        reqPlaceOrderListVo.setPreStatus(PlaceConstants.PLACE_PREORDER_STATUS);
        //预定库存，返回销售计划信息
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = placeOrderService.lockTbBizPlaceUnitSalePlanEx(reqPlaceOrderListVo, PlaceConstants.PLACE_ORDER_STATUS);
        String errorString = "";
        if(CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)){
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                if(!tbBizPlaceUnitSalePlan.getStatus().equals(PlaceConstants.PLACE_PREORDER_STATUS)){
                    errorString = tbBizPlaceUnitSalePlan.getPlaceUnitName() + "的" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime())+"时段已经售出！";
                    return APIResponse.returnFail(errorString);
                }
            }
        }
        else {
            return APIResponse.returnFail("不存在该销售计划，订场无效！");
        }


        BigDecimal debit = new BigDecimal(0);
        BigDecimal currDebit = new BigDecimal(0);

        BigDecimal originPrice = new BigDecimal(0.00);
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            debit = debit.add(tbBizPlaceUnitSalePlan.getMemberPrice());//获取会员真实的订单总价
            currDebit = currDebit.add(tbBizPlaceUnitSalePlan.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);
            /**订单原价**/
            originPrice = originPrice.add(tbBizPlaceUnitSalePlan.getPrice());
        }
        reqPlaceOrderInfo.setOriginPrice(originPrice);

        debit = debit.setScale(2, BigDecimal.ROUND_HALF_UP);

        try {
            if(debit.compareTo(new BigDecimal(0)) == 0){
                throw  new BizException(PlaceErrorCodeEnum.ORDER_MONEY_IS_ZERO);//抛出异常回滚
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BizException(PlaceErrorCodeEnum.ORDER_MONEY_IS_ZERO);
        }

        reqPlaceOrderInfo.setPrimePrice(debit);//订单原价
        //获取会员卡信息
        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        try {
            tbBizPlaceMemberCard = placeMemberService.getPlaceMemberCardInfo(reqPlaceOrderInfo.getCardNo(),reqPlaceOrderInfo.getPlaceId(),reqPlaceOrderInfo.getUid());
            if(tbBizPlaceMemberCard == null){
                throw  new BizException(PlaceErrorCodeEnum.CARD_DOES_NOT_EXIST);//抛出异常回滚
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw  new BizException(PlaceErrorCodeEnum.CARD_DOES_NOT_EXIST);
        }

        Long startTime = tbBizPlaceMemberCard.getAvailableStartTime().getTime();
        Long endTime = tbBizPlaceMemberCard.getAvailableEndTime().getTime();
        Long salePlanStartDate = tbBizPlaceUnitSalePlanList.get(0).getStartTime().getTime();
        Long salePlanEndDate = tbBizPlaceUnitSalePlanList.get(tbBizPlaceUnitSalePlanList.size() - 1).getEndTime().getTime();

        try {
            if(!(startTime <= salePlanStartDate && endTime >= salePlanEndDate) ){//判断是否过期
                throw  new BizException(PlaceErrorCodeEnum.CARD_IS_EXPIRED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw  new BizException(PlaceErrorCodeEnum.CARD_IS_EXPIRED);
        }

        /**会员卡配合优惠券抵扣**/
        if (result){
            reqPlaceOrderInfo = payTypeHandle(reqPlaceOrderInfo, tbBizPlaceMemberCard,  debit);
            currDebit = reqPlaceOrderInfo.getDisCountBeforeAmount();
            debit = reqPlaceOrderInfo.getDisCountAfterAmount();//记录原价减去优惠券金额
        }


        //储值赠送卡处理
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(reqPlaceOrderInfo.getCardNo());
        TbBizPlaceMemberCard tbBizPlaceMemberCardAfter = new TbBizPlaceMemberCard();

        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();

        //储值卡
        if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal amount = null;
            try {
                amount = tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if(amount.compareTo(debit) < 0){
                    throw new BizException(PlaceErrorCodeEnum.BALANCE_NOT_ENOUGH);//抛出异常回滚
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
                throw new BizException(PlaceErrorCodeEnum.BALANCE_NOT_ENOUGH);
            }

            //本金足够，扣除本金
            if(tbBizPlaceMemberCard.getSurplusAmount().compareTo(debit) > 0){
                BigDecimal subtract = tbBizPlaceMemberCard.getSurplusAmount().subtract(debit);
                tbBizPlaceMemberCardAfter.setSurplusAmount(subtract);
                tbBizPlaceMemberCardAfter.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            }
            //本金不足够，再扣除赠送金额
            else {
                BigDecimal subtractValue = debit.subtract(tbBizPlaceMemberCard.getSurplusAmount());
                tbBizPlaceMemberCardAfter.setSurplusAmount(new BigDecimal(0));
                BigDecimal surplusGiveAmountTemp = tbBizPlaceMemberCard.getSurplusGiveAmount();
                BigDecimal surplusGiveAmount = surplusGiveAmountTemp.subtract(subtractValue);
                tbBizPlaceMemberCardAfter.setSurplusGiveAmount(surplusGiveAmount);
            }
            reqPlaceOrderInfo.getPayInfos().get(0).setAmount(debit);
            tbBizPlaceMemberOpHistory.setAmount(debit);//设置会员价

        }
        //折扣卡
        else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal amount = tbBizPlaceMemberCard.getSurplusAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal discountAmount = null;

            if (!result){
                Double temp = new Double(tbBizPlaceMemberCard.getDiscount()) / 100;
                BigDecimal discount = new BigDecimal(temp);
                discountAmount =  debit.multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
            }else{
                 discountAmount = debit;
            }


            try {
                if(amount.compareTo(discountAmount) < 0){
                    throw new BizException(PlaceErrorCodeEnum.BALANCE_NOT_ENOUGH);
                }
            }
            catch (Exception e){
                logger.warn(e.getMessage());
                throw new BizException(PlaceErrorCodeEnum.BALANCE_NOT_ENOUGH);
            }

            BigDecimal subtract = tbBizPlaceMemberCard.getSurplusAmount().subtract(discountAmount);
            tbBizPlaceMemberCardAfter.setSurplusAmount(subtract);
            reqPlaceOrderInfo.getPayInfos().get(0).setAmount(discountAmount);//实际支付价格
            tbBizPlaceMemberOpHistory.setAmount(discountAmount);//设置为折扣价
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        }
        //储值折扣卡
        else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){

            BigDecimal discountAmount = null;
            if (!result){
                Double temp = new Double(tbBizPlaceMemberCard.getDiscount()) / 100;
                BigDecimal discount = new BigDecimal(temp);
                discountAmount = debit.multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
            }else{
                discountAmount = debit;
            }
            debit = discountAmount;
            //Double temp = new Double(tbBizPlaceMemberCard.getDiscount()) / 100;
            //BigDecimal discount = new BigDecimal(temp);
           // BigDecimal amount = null;
           // BigDecimal discountAmount = debit.multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
            BigDecimal amount = null;
            try {
                amount = tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if(amount.compareTo(discountAmount) < 0){
                    throw new BizException(PlaceErrorCodeEnum.BALANCE_NOT_ENOUGH);//抛出异常回滚
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
                throw new BizException(PlaceErrorCodeEnum.BALANCE_NOT_ENOUGH);
            }

            //本金足够，扣除本金
            if(tbBizPlaceMemberCard.getSurplusAmount().compareTo(debit) > 0){
                BigDecimal subtract = tbBizPlaceMemberCard.getSurplusAmount().subtract(debit);
                tbBizPlaceMemberCardAfter.setSurplusAmount(subtract);
                tbBizPlaceMemberCardAfter.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            }
            //本金不足够，再扣除赠送金额
            else {
                BigDecimal subtractValue = debit.subtract(tbBizPlaceMemberCard.getSurplusAmount());
                tbBizPlaceMemberCardAfter.setSurplusAmount(new BigDecimal(0));
                BigDecimal surplusGiveAmountTemp = tbBizPlaceMemberCard.getSurplusGiveAmount();
                BigDecimal surplusGiveAmount = surplusGiveAmountTemp.subtract(subtractValue);
                tbBizPlaceMemberCardAfter.setSurplusGiveAmount(surplusGiveAmount);
            }
            reqPlaceOrderInfo.getPayInfos().get(0).setAmount(debit);
            tbBizPlaceMemberOpHistory.setAmount(debit);//设置会员价

        }

        placeMemberService.updatePlaceMemberCardInfo(tbBizPlaceMemberCardExample,tbBizPlaceMemberCardAfter);

        reqPlaceOrderInfo.setOrderAmount(currDebit);

        //获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqPlaceOrderInfo.getUid());
        //获取流水号
        String no = CommonUtils.generateNo(reqPlaceOrderInfo.getPlaceId());
        reqPlaceOrderInfo.setOrderNo(orderNo);

        //插入流水记录表
        tbBizPlaceMemberOpHistory.setNo(no);
        tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
        tbBizPlaceMemberOpHistory.setUid(reqPlaceOrderInfo.getUid());

        Integer uid = reqPlaceOrderInfo.getUid();
        RespUserInfoDetail userInfo = null;
        if (null != uid){
            /**获取用户基本信息**/
            APIResponse<RespUserInfoDetail> userInfoDetail = userServiceFacade.queryUserInfoDetail(uid);
            if (null != userInfoDetail){
                userInfo= userInfoDetail.getData();
                if (null != userInfo){
                    tbBizPlaceMemberOpHistory.setUserName(userInfo.getNickName());
                    tbBizPlaceMemberOpHistory.setMobile(userInfo.getMobile());
                }
            }
        }else{
            tbBizPlaceMemberOpHistory.setUserName("uid为null");
        }

        tbBizPlaceMemberOpHistory.setUserName(reqPlaceOrderInfo.getUserInfo().getNickName());
        tbBizPlaceMemberOpHistory.setMobile(reqPlaceOrderInfo.getUserInfo().getMobile());
        tbBizPlaceMemberOpHistory.setInnerCardNo(reqPlaceOrderInfo.getCardNo());
        tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard.getCardName());
        tbBizPlaceMemberOpHistory.setOpTypeName("APP-" + iBaseService.getCommonDataCache("cagetory" + reqPlaceOrderInfo.getCategoryId().toString()) + "场地费用");
        tbBizPlaceMemberOpHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
        tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCardAfter.getSurplusAmount());
        tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCardAfter.getSurplusGiveAmount());
        tbBizPlaceMemberOpHistory.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_CONSUMER);
        tbBizPlaceMemberOpHistory.setMemo("会员卡消费");
        tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_CONSUMER);
        tbBizPlaceMemberOpHistory.setCreateUid(reqPlaceOrderInfo.getUserInfo().getUid());
        tbBizPlaceMemberOpHistory.setPayType(PlaceConstants.PAY_WAY_FOR_CARD);
        tbBizPlaceMemberOpHistory.setPlatform(reqPlaceOrderInfo.getPlatformType());

        int platformType = reqPlaceOrderInfo.getPlatformType().intValue();
        if (platformType == 1 || platformType == 2 || platformType == 3 || platformType == 4 || platformType == 6 || platformType == 7){
            tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_COMMONPAY);
        }

        tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        tbBizPlaceMemberOpHistory.setOpBeforeNumbers(0);
        tbBizPlaceMemberOpHistory.setOpAfterNumbers(0);
        tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);

        /**设置服务开关
         * ServiceSwitch 0:不支付，1:支付
         * **/
        TbCommonParameter parameter1 = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
        if (parameter1 != null && parameter1.getParameterValue() != null) {
            reqPlaceOrderInfo.setServiceSwitch(Integer.valueOf(parameter1.getParameterValue()));
        }

        if (reqPlaceOrderInfo.getServiceSwitch().equals(0)){
            //插入订单明细表
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
                tbBizPlaceOrderItem.setPlaceOrderId(orderNo);
                tbBizPlaceOrderItem.setUnitSalePlanId(tbBizPlaceUnitSalePlan.getId());
                tbBizPlaceOrderItem.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
                tbBizPlaceOrderItem.setConsumeTime(tbBizPlaceUnitSalePlan.getDate());//消费时间
                if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
                    Double temp = new Double(tbBizPlaceMemberCard.getDiscount()) / 100;
                    BigDecimal discount = new BigDecimal(temp);
                    BigDecimal discountAmount = tbBizPlaceUnitSalePlan.getMemberPrice().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
                    tbBizPlaceOrderItem.setSalePrice(discountAmount);//设置打折后会员价
                }
                else {
                    tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getMemberPrice());//设置会员价
                }

                tbBizPlaceOrderItem.setVersion(tbBizPlaceUnitSalePlan.getVersion());
                tbBizPlaceOrderItem.setTicketCount(1);
                tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
                tbBizPlaceOrderItem.setUseType((byte) 3);
                tbBizPlaceOrderItem.setGoodsId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                tbBizPlaceOrderItem.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
                tbBizPlaceOrderItem.setSurplusGoodsCount(1);
                tbBizPlaceOrderItem.setTotalGoodsCount(1);
                tbBizPlaceOrderItem.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
                tbBizPlaceOrderItem.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());
                tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceUnitSalePlan.getPrice());
                tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
                tbBizPlaceOrderItem.setCategoryId(reqPlaceOrderInfo.getCategoryId());
                tbBizPlaceOrderItemMapper.insertSelective(tbBizPlaceOrderItem);
            }
          
            //插入订单支付方式明细表
            if(CollectionUtils.isNotEmpty(payInfos)){
                Integer payWayBoss = Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS);
                for (ReqPayInfo payInfo : payInfos) {
                    TbBizPlacePayItem record = new TbBizPlacePayItem();
                    record.setPlaceOrderId(orderNo);
                    record.setAmount(payInfo.getAmount());
                    record.setPayType(payInfo.getPayId());
                    record.setAdminPayType(PlaceOrderUtil.getAdminPayType(payInfo.getPayId()));
                    if (null != payInfo.getPayId() &&
                            PlaceConstants.PAY_WAY_FOR_CARD.equals(payInfo.getPayId()) &&
                            Constants.BYTE_ONE == tbBizPlaceMemberCard.getIsOldMember()){
                        // 与场馆原老板结算的老会员支付方式做特殊处理
                        record.setPayType(payWayBoss);
                        record.setAdminPayType(payWayBoss);
                        payInfo.setSubjectCode(tbBizPlaceMemberCard.getInnerCardNo());
                    }
                    if (null != payInfo.getPayId() &&
                            PlaceConstants.PAY_WAY_FOR_COUPON.equals(payInfo.getPayId())){
                        record.setSubjectCode(payInfo.getSubjectCode());
                    }
                    if (null != payInfo.getPayId() &&
                            PlaceConstants.PAY_WAY_FOR_CARD.equals(payInfo.getPayId())){
                        payInfo.setSubjectCode(tbBizPlaceMemberCard.getInnerCardNo());
                    }
                    record.setAmountType(PlaceConstants.DEBIT_TYPE);
                    tbBizPlacePayItemMapper.insertSelective(record);
                }
            }
        }

        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();
        tbBizPlaceOrder.setUid(reqPlaceOrderInfo.getUid());
        if (null != reqPlaceOrderInfo.getUid()){
           if(null != userInfo){
                tbBizPlaceOrder.setCustomerName(userInfo.getNickName());
                tbBizPlaceOrder.setMobile(userInfo.getMobile());
            }
        }else{
            tbBizPlaceOrder.setCustomerName("散客");
        }
        Date date = new Date();
        tbBizPlaceOrder.setPlaceOrderId(orderNo);
        tbBizPlaceOrder.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        tbBizPlaceOrder.setCategoryId(reqPlaceOrderInfo.getCategoryId());
        tbBizPlaceOrder.setDate(date);
        /*if (result){
            tbBizPlaceOrder.setDebit(reqPlaceOrderInfo.getPrimePrice());
        }else {
            tbBizPlaceOrder.setDebit(currDebit);
        }*/
        tbBizPlaceOrder.setDebit(originPrice);
        /**重新赋值订单原价**/
        tbBizPlaceOrder.setDebit(reqPlaceOrderInfo.getOriginPrice());

        tbBizPlaceOrder.setOrderTime(date);
        tbBizPlaceOrder.setPayStatus(PlaceConstants.PAY_STATUS);
        tbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
        tbBizPlaceOrder.setDescrible(reqPlaceOrderInfo.getDescribe());
        tbBizPlaceOrder.setCreateTime(date);
        tbBizPlaceOrder.setOrderStatusChangeDate(date);
        tbBizPlaceOrder.setPlatform(reqPlaceOrderInfo.getPlatformType());
        tbBizPlaceOrder.setOrderUse(PlaceConstants.NO);
        tbBizPlaceOrder.setPaymentTime(date);
        tbBizPlaceOrder.setIsEffective(PlaceConstants.YES);
        tbBizPlaceOrder.setUseType(PlaceConstants.ORDER_USE_APP_BILLING);
        tbBizPlaceOrder.setBusinessMode(tbBizPlace.getBusinessMode());//场馆
        tbBizPlaceOrder.setIsMember((byte)1);
        tbBizPlaceOrder.setInnerCardNo(reqPlaceOrderInfo.getCardNo());
        /**1:IOS 2:Android3:微信4.普通浏览器6.QQ7:微信小程序**/
        Byte sourceType = PlaceOrderUtil.orderSourceTypeByPlatform(platformType);
        if (null != sourceType){
            tbBizPlaceOrder.setSourceType(sourceType);
        }
        Byte orderChannel = PlaceOrderUtil.orderChannelByPlatform(platformType);
        if (null != orderChannel){
            tbBizPlaceOrder.setOrderChannel(orderChannel);
        }

        //设置回调方式
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_ORDER_CALLBACK_TYPE.getCode());
        Integer callbackType = 0;
        if (parameter != null && parameter.getParameterValue() != null){
            callbackType = Integer.valueOf(parameter.getParameterValue());
        }
        reqPlaceOrderInfo.setCallbackType(callbackType);
        reqPlaceOrderInfo.setTradeType((byte)0);
        reqPlaceOrderInfo.setUseType(PlaceConstants.ORDER_USE_APP_BILLING);

        if (reqPlaceOrderInfo.getServiceSwitch().equals(1)) {
            /**拆分订单明细**/
            OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
            orderItemCostDTO.setOrderType(1);
            orderItemCostDTO.setPayInfoList(payInfos);
            orderItemCostDTO.setTbBizPlaceUnitSalePlanList(tbBizPlaceUnitSalePlanList);
            orderItemCostDTO.setReqPlaceOrderInfo(reqPlaceOrderInfo);
            orderItemCostDTO.setTbBizPlaceMemberCard(tbBizPlaceMemberCard);
            orderItemCostDTO.setRespCoupon(respCoupon);

            APIResponse orderItemCostResp = apiPlaceOrderService.setOrderItemCostService(orderItemCostDTO);
            if (null != orderItemCostResp) {
                return APIResponse.returnFail("订单明细执行异常！");
            }

            APIResponse payItemResp = apiPlaceOrderService.setOrderPayItemCostService(orderItemCostDTO);
            if (null != payItemResp) {
                return APIResponse.returnFail("付款明细执行异常！");
            }

//            /**
//             * 1、储值卡单一支付不参与优惠? 储值卡需要记会员优惠
//             * **/
//            if (tbBizPlaceMemberCard.getCardType().equals(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE) &&
//                    reqPlaceOrderInfo.getPayInfos().size()==1){
//
//            }else{
                /***优惠明细**/
                APIResponse orderDiscountItemCostResp = apiPlaceOrderService.setOrderDiscountItemCostService(orderItemCostDTO);
                if (null != orderDiscountItemCostResp){
                    APIResponse.returnFail("优惠明细异常！");
                }

        }

        //通知订单系统，生成订单，需要抛出异常
        RespPreOrder respPreOrder = null;
        APIResponse<RespPreOrder> respPreOrderAPIResponse = null;
        try {
            respPreOrderAPIResponse = noticeOrderSystem(reqPlaceOrderInfo, tbBizPlace, tbBizPlaceUnitSalePlanList,true);
            //存储订单系统的订单号
            if(respPreOrderAPIResponse != null && respPreOrderAPIResponse.isRet()){
                respPreOrder = respPreOrderAPIResponse.getData();
                tbBizPlaceOrder.setOrderNo(respPreOrder.getOrderNo());
                tbBizPlaceOrderMapper.insertSelective(tbBizPlaceOrder);
            }
            else {
                throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
            }
        }
        catch (Exception e){
            if(respPreOrderAPIResponse != null && !respPreOrderAPIResponse.isRet()){
                logger.warn("uid：{} ，error：{} " ,reqPlaceOrderInfo.getUid(),respPreOrderAPIResponse.getErrmsg());
            }
            else {
                logger.warn("uid：{} ，error：{} " ,reqPlaceOrderInfo.getUid(),e.getMessage());
            }

            if (respPreOrderAPIResponse.getErrcode() == 21012){
                throw new BizException(PlaceErrorCodeEnum.TICKET_PAY_CONFIG_ERROR);
            }

            if ("该优惠券不能使用".equals(respPreOrderAPIResponse.getErrmsg())){
                throw new BizException(PlaceErrorCodeEnum.COUPON_NOT_USE);
            }

            throw new BizException(PlaceErrorCodeEnum.ORDER_SYSTEM_ERROR);
        }

        //报名人数加1、更新索引、消息推送
        paySuccessOperate(reqPlaceOrderInfo, tbBizPlaceUnitSalePlanList);


        return APIResponse.returnSuccess(respPreOrder);
    }

    /**
     * 记录订单回调
     * @param orderOperate
     */
    @Async
    public void orderCallBackHistory(ReqOrderOperate orderOperate) {
        OrderHistoryDTO orderHistoryDTO = new OrderHistoryDTO();
        orderHistoryDTO.setReqOrderOperate(orderOperate);
        /**是退款 还是支付成功**/
        orderHistoryDTO.setOrderType(orderOperate.getOperateType());
        apiPlaceOrderService.insertOrderHistory(orderHistoryDTO);
    }

    /**
     * 会员卡结合优惠券支付
     * @param reqPlaceOrderInfo
     * @param tbBizPlaceMemberCard
     * @param debit 订单金额
     * @return
     */
    private ReqPlaceOrderInfo payTypeHandle(ReqPlaceOrderInfo reqPlaceOrderInfo,TbBizPlaceMemberCard tbBizPlaceMemberCard, BigDecimal debit){
        List<ReqPayInfo> payInfos = reqPlaceOrderInfo.getPayInfos();
        for (ReqPayInfo payInfo : payInfos) {
            payInfo.setSportType(reqPlaceOrderInfo.getCategoryId().byteValue());
            if (payInfo.getPayId().equals(PlaceConstants.PAY_WAY_FOR_COUPON)){
                /** 会员卡类型： 储值卡 1*/
                payInfo.setOrderType(CouponOrderType.PLACE.getId().byteValue());
                if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE.equals(tbBizPlaceMemberCard.getCardType())){
                    reqPlaceOrderInfo.setDisCountBeforeAmount(debit);//订单价格
                    if (debit.compareTo(payInfo.getAmount()) >=0){
                        debit = debit.subtract(payInfo.getAmount());//订单金额-优惠券金额
                    }else{
                        debit = new BigDecimal(0);
                    }

                    reqPlaceOrderInfo.setDisCountAfterAmount(debit);//用优惠券抵扣后订单金额
                /** 会员状态： 折扣卡 2*/
                /** 会员状态： 储值折扣卡*/
                }else if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
                   // reqPlaceOrderInfo.setDisCountBeforeAmount(debit);//订单价格打折以后价格
                    Double temp = new Double(tbBizPlaceMemberCard.getDiscount()) / 100;
                    BigDecimal discount = new BigDecimal(temp);
                    debit = debit.multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
                    reqPlaceOrderInfo.setDisCountBeforeAmount(debit);//订单价格打折以后价格
                    if (debit.compareTo(payInfo.getAmount()) >=0){
                        debit = debit.subtract(payInfo.getAmount());//订单金额-优惠券金额
                    }else{
                        debit = new BigDecimal(0);
                    }
                    reqPlaceOrderInfo.setDisCountAfterAmount(debit.setScale(2,BigDecimal.ROUND_HALF_UP));//用优惠券抵扣后订单金额
                }
            }
        }
        return reqPlaceOrderInfo;

    }
    private APIResponse memberPayVerification(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanListTemp,List<RespCardInfo> cardInfos,RespPlaceOrderInfo respPlaceOrderInfo){
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = new ArrayList<>();
        tbBizPlaceUnitSalePlanList.addAll(tbBizPlaceUnitSalePlanListTemp);
        if(cardInfos == null){
            return null;
        }

        Comparator<TbBizPlaceUnitSalePlan> comparator = new Comparator<TbBizPlaceUnitSalePlan>() {
            @Override
            public int compare(TbBizPlaceUnitSalePlan o1, TbBizPlaceUnitSalePlan o2) {
                return o1.getStartTime().compareTo(o2.getStartTime());
            }
        };
        Collections.sort(tbBizPlaceUnitSalePlanList, comparator);//按照开始时间排序
        int end = tbBizPlaceUnitSalePlanList.size() -1;
        for (RespCardInfo cardInfo : cardInfos) {
            Long startTime = DateUtils.tranferDateStringToDate(cardInfo.getAvailableStartTime()).getTime();
            Long endTime = DateUtils.tranferDateStringToDate(cardInfo.getAvailableEndTime()).getTime();
            Long salePlanStartDate = tbBizPlaceUnitSalePlanList.get(0).getStartTime().getTime();
            Long salePlanEndDate = tbBizPlaceUnitSalePlanList.get(end).getEndTime().getTime();
            boolean isExpired = true;
            boolean isEnough = true;
            if(startTime <= salePlanStartDate && endTime >= salePlanEndDate ){//判断是否过期
                isExpired = false;
            }

            //储值赠送卡处理
            if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE.equals(cardInfo.getCardType())){
                BigDecimal amount = null;
                amount = cardInfo.getSurplusAmount().add(cardInfo.getSurplusGiveAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if(amount.compareTo(respPlaceOrderInfo.getOrderMemberAmount()) < 0){
                    isEnough = false;
                }
            }
            //储值折扣卡处理
            else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(cardInfo.getCardType())){
                BigDecimal amount = cardInfo.getSurplusAmount().setScale(2, BigDecimal.ROUND_HALF_UP);
                Double temp = new Double(cardInfo.getDiscount()) / 100;
                BigDecimal discount = new BigDecimal(temp);
                BigDecimal discountAmount =  respPlaceOrderInfo.getOrderMemberAmount().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
                respPlaceOrderInfo.setOrderDiscountAmount(discountAmount);
                if(amount.compareTo(discountAmount) < 0){
                    isEnough = false;
                }

            }
            //储值赠送折扣卡处理
            else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(cardInfo.getCardType())){
                Double temp = new Double(cardInfo.getDiscount()) / 100;
                BigDecimal discount = new BigDecimal(temp);
                BigDecimal amount = cardInfo.getSurplusAmount().add(cardInfo.getSurplusGiveAmount()).setScale(2, BigDecimal.ROUND_HALF_UP);
                BigDecimal discountAmount = respPlaceOrderInfo.getOrderMemberAmount().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP);
                respPlaceOrderInfo.setOrderDiscountAmount(discountAmount);
                if(amount.compareTo(discountAmount) < 0){
                    isEnough = false;
                }
            }

            if(!isExpired && isEnough){
                //会员卡可用
                cardInfo.setState(PlaceConstants.CARD_ENABLE);
            }
            else if(isExpired && isEnough){
                //会员卡余额充足，会员卡不在使用时间内
                cardInfo.setState(PlaceConstants.CARD_EXPIRED);
            }
            else if(!isExpired && !isEnough){
                //会员卡在使用时间内，会员卡余额不足
                cardInfo.setState(PlaceConstants.CARD_NOT_ENOUGH);
            }
            else if(isExpired && !isEnough){
                //会员卡余额不足同时不在使用时间内
                cardInfo.setState(PlaceConstants.CARD_EXPIRED_AND_NOT_ENOUGH);
            }
        }
        return null;
    }


    /**
     * 会员卡支付成功回调
     * @param reqPlaceOrderInfo
     * @param tbBizPlaceUnitSalePlanList
     * @return
     */

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse paySuccessOperate(ReqPlaceOrderInfo reqPlaceOrderInfo,List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList){
        //馆报名人数加一
        Map<String,Object> map = new HashMap<>();
        map.put("placeId", reqPlaceOrderInfo.getPlaceId());
        map.put("addSignupCount", 1);
        placeMapper.updateCount(map);

        TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(reqPlaceOrderInfo.getPlaceId());

        //加入消息推送，提示订场成功
        PlaceMessage placeMessage = new PlaceMessage();
        placeMessage.setOrderNo(reqPlaceOrderInfo.getOrderNo());
        placeMessage.setOrderType(1);
        List<Integer> uids = new ArrayList<>();
        uids.add(reqPlaceOrderInfo.getUid());
        placeMessage.setUids(uids);
        String salePlanDate = DateUtils.transferDateToString(tbBizPlaceUnitSalePlanList.get(0).getDate());
        String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
        placeMessage.setDate(salePlanDateNew);
        placeMessage.setPlaceName(tbBizPlace.getName());
        placeMessage.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        placeMessage.setPayType(PlaceConstants.PAY_WAY_FOR_CARD);
        Cagetory cagetory =cagetoryMapper.selectByPrimaryKey(reqPlaceOrderInfo.getCategoryId());
        placeMessage.setCategoryValue(cagetory.getName());
        boolean result = pushMessageOperate(placeMessage);
        //加入消息队列进行异步消息推送处理
        if(!result){
            mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
        }

        //发送短信
        smsSendOperate(null,tbBizPlaceUnitSalePlanList,reqPlaceOrderInfo.getUid(),tbBizPlace);
        ReqOrderOperate orderOperate = new ReqOrderOperate();
        orderOperate.setOperateType(2); //订单完成
        orderOperate.setOrderNo(reqPlaceOrderInfo.getOrderNo());
        orderOperate.setPlatformType(reqPlaceOrderInfo.getPlatformType());
        orderOperate.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        /**会员卡支付成功回调**/
        orderCallBackHistory(orderOperate);

        commonService.mqSendSportService(orderOperate.getOrderNo(),1);
        /*try {
            this.searchService.addPlaceIndex(tbBizPlace, null);
        } catch (Exception e) {
            logger.error("增加索引失败，加入消息队列进行处理!");
            //加入消息队列进行异步索引添加处理
            TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
            tbBizPlaceVo.setTbBizPlace(tbBizPlace);
            mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
        }*/
        return APIResponse.returnSuccess();

    }


    /**
     * 订场成功发送短信通知用户
     * @param placeOrderSalePlanList
     * @param uid
     * @param tbBizPlace
     * @return
     */
    @Async
    private boolean smsSendOperate(List<PlaceOrderSalePlan> placeOrderSalePlanList,List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList,Integer uid, TbBizPlace tbBizPlace){
        if(CollectionUtils.isEmpty(placeOrderSalePlanList) && CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanList)){
            return false;
        }
        List<String> mobiles=new ArrayList<>();
        List<String> params=new ArrayList<>();
        String phone="";
        String [] args = new String[3];
        args[0] = "";
        args[1] = "";
        args[2] = "";
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            phone=placeAttach.getBookingConsultPhone();
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            phone=parameterVo!=null?parameterVo.getParameterValue():"";
        }

        if(CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)){
            Comparator<TbBizPlaceUnitSalePlan> comparator = new Comparator<TbBizPlaceUnitSalePlan>() {
                @Override
                public int compare(TbBizPlaceUnitSalePlan o1, TbBizPlaceUnitSalePlan o2) {
                    return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

                }
            };
            Collections.sort(tbBizPlaceUnitSalePlanList, comparator);
            String salePlanDate = DateUtils.transferDateToString(tbBizPlaceUnitSalePlanList.get(0).getDate());
            String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
            args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + tbBizPlaceUnitSalePlanList.get(0).getCategoryId().toString());
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                args[1] +=tbBizPlaceUnitSalePlan.getPlaceUnitName()+" "+ " " + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()) + "、";
            }
            args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";
            args[2] = phone;
        }
        else if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            Comparator<PlaceOrderSalePlan> comparator = new Comparator<PlaceOrderSalePlan>() {
                @Override
                public int compare(PlaceOrderSalePlan o1, PlaceOrderSalePlan o2) {
                    return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

                }
            };
            Collections.sort(placeOrderSalePlanList, comparator);

            String salePlanDateNew = DateUtils.tranferStringToZHCN(placeOrderSalePlanList.get(0).getDate());
            args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + placeOrderSalePlanList.get(0).getCategoryId().toString());
            for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                String startTime = placeOrderSalePlan.getStartTime();
                String endTime = placeOrderSalePlan.getEndTime();
                args[1] +=placeOrderSalePlan.getPlaceUnitName()+" "+ " " +  startTime.substring(0,startTime.length()-3) + "-" + endTime.substring(0,endTime.length()-3) + "、";
            }
            args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";
            args[2] = phone;
        }

        APIResponse<RespUserInfoBase> userMsg = userServiceFacade.queryUserInfo(uid);
        if(!userMsg.isRet()){
            return false;
        }
        RespUserInfoBase respUserInfoBase = userMsg.getData();
        mobiles.add(respUserInfoBase.getMobile());
        params.addAll(Arrays.asList(args));
        try {
            //placeTicketService.asyncSendSms(respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_NOTICE,args,true);
            placeSmsService.sendSms(mobiles,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,params);
        } catch(Exception e){
            logger.info("短信发送失败-------->" + e.getMessage());
            return false;
        }

        //发送短信提醒给场馆人员
        TbBizPlaceNoticeMobile messageVo = placeMessageService.getMobileDataByPlaceId(tbBizPlace.getId());
        APIResponse<RespUserInfoBase>  userInfo=userServiceFacade.queryUserInfo(uid);
        String nickName=userInfo.getData()!=null ? userInfo.getData().getNickName():"";
        if (null != messageVo){
            APIResponse<RespUserInfoBase> resPvo = userServiceFacade.queryUserInfo(uid);
            List<String> mobileList=new ArrayList<>();
            List<String> paramList=new ArrayList<>();
            String[] messageArgs = new String[4];
            messageArgs[0] = nickName;
           // messageArgs[0] = resPvo != null ? resPvo.getData().getMobile() : "";
            messageArgs[1]=args[0];
            messageArgs[2]=args[1];
            messageArgs[3]=resPvo != null ? resPvo.getData().getMobile() : "";
            mobileList.add(messageVo.getMobile());
            paramList.addAll(Arrays.asList(messageArgs));
            try {
                if (!StringUtils.isEmpty(messageVo.getMobile())) {
                    placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_REMIND, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
                }
            } catch (java.lang.Exception e) {
                logger.info("短信发送失败-------->" + e.getMessage());
            }
        }
        return true;
    }

    /**
     * 购买门票成功后短信推送
     * @param placeTicketPushOrderVo
     * @param uid
     * @param tbBizPlace
     * @return
     */
    @Async
    private boolean ticketSmsSendOperate(PlaceTicketPushOrderVo placeTicketPushOrderVo,Integer uid, TbBizPlace tbBizPlace){
        if(null == placeTicketPushOrderVo){
            return false;
        }
        List<String> mobiles=new ArrayList<>();
        List<String> params=new ArrayList<>();
        String phone="";
        String [] args = new String[3];
        args[0] = "";
        args[1] = "";
        args[2] = "";
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            phone=placeAttach.getBookingConsultPhone();
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            phone=parameterVo!=null?parameterVo.getParameterValue():"";
        }


        String salePlanDateNew = placeTicketPushOrderVo.getDate();

        args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + placeTicketPushOrderVo.getCategoryId().toString());
        List<TicketPushOrderVo> pushOrderVos = placeTicketPushOrderVo.getTicketPushOrderVos();
        if (!org.springframework.util.CollectionUtils.isEmpty(pushOrderVos)){
            for (TicketPushOrderVo TicketPushOrderVo : pushOrderVos) {
                args[1] +=TicketPushOrderVo.getTicketName() + " " + DateTimeUtils.timeToStr(TicketPushOrderVo.getStartTime()) + "-" + DateTimeUtils.timeToStr(TicketPushOrderVo.getEndTime()) + "、";
            }
        }
        args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";
        args[2] = phone;


        APIResponse<RespUserInfoBase> userMsg = userServiceFacade.queryUserInfo(uid);
        if(!userMsg.isRet()){
            return false;
        }
        RespUserInfoBase respUserInfoBase = userMsg.getData();
        mobiles.add(respUserInfoBase.getMobile());
        params.addAll(Arrays.asList(args));
        try {
          //placeTicketService.asyncSendSms(respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_TICKET_NOTICE,args,true);
            placeSmsService.sendSms(mobiles,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_TICKET_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,params);
        } catch(Exception e){
            logger.info("短信发送失败-------->" + e.getMessage());
            return false;
        }

        //发送短信提醒给场馆人员
        /*
        TbBizPlaceNoticeMobile messageVo = placeMessageService.getMobileDataByPlaceId(tbBizPlace.getId());
        if (null!=messageVo){
            APIResponse<RespUserInfoBase> resPvo = userServiceFacade.queryUserInfo(uid);
            List<String> mobileList=new ArrayList<>();
            List<String> paramList=new ArrayList<>();
            String[] messageArgs = new String[3];
            messageArgs[0] = resPvo != null ? resPvo.getData().getMobile() : "";
            messageArgs[1]=args[0];
            messageArgs[2]=args[1];
            mobileList.add(messageVo.getMobile());
            paramList.addAll(Arrays.asList(messageArgs));
            try {
                if (!StringUtils.isEmpty(messageVo.getMobile())){
                    //placeTicketService.asyncSendSmsToOperator(messageVo.getMobile(),respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_REMIND, messageArgs, true);
                    placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_REMIND, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
                }
            } catch (java.lang.Exception e) {
                logger.info("短信发送失败-------->" + e.getMessage());
            }
        }
        */
        return true;
    }


    /**
     * 商家端退款
     * @param reqPlaceOrderId
     * @param operateUid
     * @param customerId
     * @param placeId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeRefund(String reqPlaceOrderId, Integer operateUid, Integer placeId,Integer customerId) throws Exception {
        if (StringUtils.isEmpty(reqPlaceOrderId) && !StringUtils.isEmpty(operateUid)) {
            return APIResponse.returnFail("退款失败,订单号,Uid,placeId不能为空！");
        }
        //查询订单
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
        List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);

        //查询订单支付方式
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
        List<TbBizPlacePayItem> tbBizPlacePayItems = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);


        //订单明细
        TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
        tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);

        if (CollectionUtils.isEmpty(tbBizPlaceOrders)) {
            return APIResponse.returnFail("查不到此订单！");
        }
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("订单明细为空！");
        }

        TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrders.get(0);

        //未付款 未支付
        if(tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS)
                && tbBizPlaceOrder.getOrderStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
            //订场业务才可以更改库存
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                    || tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
                    ||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
                boolean flag = placeOrderService.cancelBook(tbBizPlaceOrder.getPlaceOrderId());
                if (flag){
                    return APIResponse.returnSuccess("取消预订成功！");
                } else {
                    throw new BizException("取消预订失败");
                }
            }
        }

        if (tbBizPlaceOrder.getOrderStatus().intValue() > 3){
            return APIResponse.returnFail("当前订单状态不支持退款.");
        }
        if (CollectionUtils.isEmpty(tbBizPlacePayItems)) {
            return APIResponse.returnFail("支付明细为空！");
        }


        TbBizPlaceOrderItem tbBizPlaceOrderItem = tbBizPlaceOrderItems.get(0);
        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);

       if (!StringUtils.isEmpty(tbBizPlacePayItem)){
           if (tbBizPlacePayItem.getAmountType().intValue() ==PlaceConstants.CREDIT_TYPE){
        	   return APIResponse.returnFail("不允许重复退款!");
           }
       }

        if (PlaceConstants.SOURCE_TYPE_SCENEPAY.intValue() == tbBizPlaceOrder.getSourceType().intValue()
                && PlaceConstants.PLACE_ADMIN_PAY_TYPE.intValue() == tbBizPlaceOrder.getOrderChannel().intValue()){
            //商家端订单退款
            this.adminOrderRefund(tbBizPlaceOrder,tbBizPlaceOrderItems,tbBizPlacePayItems,reqPlaceOrderId,operateUid);
        }  else {//调用线上退款
            if (StringUtils.isEmpty(customerId)){
                return APIResponse.returnFail("线上订单退款customerId不能为null");
            }
            ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
            reqOrderOperate.setOrderNo(reqPlaceOrderId);
            reqOrderOperate.setPlaceId(placeId);
            reqOrderOperate.setUid(customerId);
            reqOrderOperate.setOperateType(PlaceConstants.ORDER_UNSUBSCRIBE_OPERATE);
            reqOrderOperate.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);
            reqOrderOperate.setPlatformType(PlatformTypeEnum.BACKSTAGE.getId());
            try{
                APIResponse response = this.orderOperate(reqOrderOperate);
                //if (response.isRet()){
                    /*if(tbBizPlaceOrders!=null&&tbBizPlaceOrders.size()>0){
                        String [] args=new String[1];
                        args[0]=tbBizPlaceOrders.get(0).getDebit().toString();
                        Result result = smsService.sendMessageToPhone(tbBizPlaceOrder.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE,args,true);
                        if (result.isStatus()){
                            logger.info("================短信发送成功！");
                        } else {
                            logger.warn("================短信发送失败！");
                        }
                    }*/
                //}
                if (response.isRet()){
                    return response;
                }else {
                    throw new Exception(response.getErrmsg());
                }
            }catch (Exception e){
                throw e;
            }
        }
        try {
            placeInnerService.syncSalePlanPriceForRefundOrder(tbBizPlaceOrder.getPlaceOrderId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return APIResponse.returnSuccess();
    }
    
    /**
     * 商家端包场子订单退款
     * @param reqPlaceOrderId
     * @param operateUid
     * @param customerId
     * @param placeId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> placeBlockRefund(String reqPlaceOrderId, Integer operateUid, Integer placeId,Integer customerId) throws Exception {
        if (StringUtils.isEmpty(reqPlaceOrderId) && !StringUtils.isEmpty(operateUid)) {
            return APIResponse.returnFail("退款失败,订单号,Uid,placeId不能为空！");
        }
        //查询订单
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
        List<TbBizPlaceOrder> tbBizPlaceOrders = this.tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);

        //查询订单支付方式
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
        List<TbBizPlacePayItem> tbBizPlacePayItems = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);


        //订单明细
        TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
        tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(reqPlaceOrderId);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);

        if (CollectionUtils.isEmpty(tbBizPlaceOrders)) {
            return APIResponse.returnFail("查不到此订单！");
        }
        if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)) {
            return APIResponse.returnFail("订单明细为空！");
        }

        TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrders.get(0);

        //未付款 未支付
        if(tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS)
                && tbBizPlaceOrder.getOrderStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
            //订场业务才可以更改库存
            if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                    || tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
                    ||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
                boolean flag = placeOrderService.cancelBook(tbBizPlaceOrder.getPlaceOrderId());
                if (flag){
                    return APIResponse.returnSuccess("取消预订成功！");
                } else {
                    throw new BizException("取消预订失败");
                }
            }
        }

        if (CollectionUtils.isEmpty(tbBizPlacePayItems)) {
            return APIResponse.returnFail("支付明细为空！");
        }


        TbBizPlaceOrderItem tbBizPlaceOrderItem = tbBizPlaceOrderItems.get(0);
        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);

//        if (!StringUtils.isEmpty(tbBizPlaceOrder.getEnableRefund())){
//            if (tbBizPlaceOrder.getEnableRefund().intValue() == 0){
//                throw new Exception("此订单不允许退款.");
//            }
//        }

        if (PlaceConstants.SOURCE_TYPE_SCENEPAY.equals(tbBizPlaceOrder.getSourceType())){
            //商家端订单退款
            this.adminBlockOrderRefund(tbBizPlaceOrder,tbBizPlaceOrderItems,tbBizPlacePayItems,reqPlaceOrderId,operateUid);
        }  else {//调用线上退款
            if (StringUtils.isEmpty(customerId)){
                return APIResponse.returnFail("线上订单退款customerId不能为null");
            }
            ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
            reqOrderOperate.setOrderNo(reqPlaceOrderId);
            reqOrderOperate.setPlaceId(placeId);
            reqOrderOperate.setUid(customerId);
            reqOrderOperate.setOperateType(PlaceConstants.ORDER_UNSUBSCRIBE_OPERATE);
            reqOrderOperate.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);
            try{
                APIResponse response = this.orderOperate(reqOrderOperate);
                //if (response.isRet()){
                    /*if(tbBizPlaceOrders!=null&&tbBizPlaceOrders.size()>0){
                        String [] args=new String[1];
                        args[0]=tbBizPlaceOrders.get(0).getDebit().toString();
                        Result result = smsService.sendMessageToPhone(tbBizPlaceOrder.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE,args,true);
                        if (result.isStatus()){
                            logger.info("================短信发送成功！");
                        } else {
                            logger.warn("================短信发送失败！");
                        }
                    }*/
                //}
                if (response.isRet()){
                    return response;
                }else {
                    throw new Exception(response.getErrmsg());
                }
            }catch (Exception e){
                throw e;
            }
        }
        //释放场地状态更新场地价格
        try {
            placeInnerService.syncSalePlanPriceForRefundOrder(tbBizPlaceOrder.getPlaceOrderId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return APIResponse.returnSuccess();
    }

    /**
     *
     */
    private void adminOrderRefund(TbBizPlaceOrder tbBizPlaceOrder,
                                  List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
                                  List<TbBizPlacePayItem> tbBizPlacePayItems,
                                  String reqPlaceOrderId,
                                  Integer operateUid) throws Exception{
        if (tbBizPlaceOrder.getPayStatus().intValue() != PlaceConstants.PAY_STATUS.intValue()
                && tbBizPlaceOrder.getOrderStatus().intValue() != PlaceConstants.ORDER_PAYED_STATUS){
            throw new BizException("该订单未支付不能退款");
        }
        BigDecimal refundPrice = new BigDecimal(0);
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
            refundPrice = refundPrice.add(tbBizPlaceOrderItem.getSalePrice());
        }
        //线下开单退款
        TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
        BeanUtils.copyProperties(tbBizPlaceOrder, newTbBizPlaceOrder);
        //修改订单状态
        newTbBizPlaceOrder.setId(tbBizPlaceOrder.getId());
        newTbBizPlaceOrder.setPlaceOrderId(reqPlaceOrderId);
        newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
        /*BigDecimal credit = new BigDecimal(0);
        if (!StringUtils.isEmpty(tbBizPlaceOrder.getHandAdjustAmount())){
            credit = tbBizPlaceOrder.getDebit().add(tbBizPlaceOrder.getHandAdjustAmount());
        }else {
            credit = tbBizPlaceOrder.getDebit();
        }*/
        newTbBizPlaceOrder.setCredit(refundPrice);//退款金额
        newTbBizPlaceOrder.setRefundTime(new Date());//退款时间

        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
            //扫码退款  订单状态 = 退款中
            newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
        }else{
            newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
            newTbBizPlaceOrder.setPayStatus(PlaceConstants.REFUNDING_STATUS);
        }

        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){//门票退款
            newTbBizPlaceOrder = this.ticketOrderRefund(tbBizPlaceOrderItems, newTbBizPlaceOrder, tbBizPlacePayItems);
        } else if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                || tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){//开单包场退款
            newTbBizPlaceOrder = this.billingAndBlockOrderRefund(tbBizPlaceOrderItems,newTbBizPlaceOrder,tbBizPlacePayItems);
        } else if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){//小商品退款
            //小商品退款
            newTbBizPlaceOrder = this.goodsOrderRefund(tbBizPlaceOrderItems, newTbBizPlaceOrder, tbBizPlacePayItems);
        }else if(tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){//购物车
			newTbBizPlaceOrder=this.shoppingCartOrderRefund(tbBizPlaceOrderItems, newTbBizPlaceOrder, tbBizPlacePayItems);
		}

        try {
            //退款日志
            TbBusinessLog log = new TbBusinessLog();
            log.setEntityId(tbBizPlaceOrder.getId());
            log.setEntityType(PlaceConstants.LOG_TYPE_PLACE_ORDER);
            log.setUid(operateUid);
            log.setLogName("商家端退款");
            log.setLogInfo("订单号：[" + tbBizPlaceOrder.getPlaceOrderId() + "]" + " 退款人：[" + tbBizPlaceOrder.getCustomerName() + "],订单金额：[" + tbBizPlaceOrder.getDebit() + "]" + "电话：[" + tbBizPlaceOrder.getMobile() + "]");
            tbBusinessLogService.insertLogInfo(log);
        } catch (Exception e) {
            throw new Exception("退款日志生成失败.");
        }

        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andOrderStatusLessThanOrEqualTo(PlaceConstants.ORDER_REFUNDING_STATUS);
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(newTbBizPlaceOrder.getPlaceOrderId());
        TbBizPlaceOrder updateTbBizPlaceOrder = new TbBizPlaceOrder();
        BeanUtils.copyProperties(newTbBizPlaceOrder,updateTbBizPlaceOrder);
        updateTbBizPlaceOrder.setId(null);//设置为空，否则报Duplicate entry 'xxx' for key 'PRIMARY'
        if (this.tbBizPlaceOrderMapper.updateByExampleSelective(newTbBizPlaceOrder,tbBizPlaceOrderExample) == 0) {
            //这里需要注意异步和同步同时到达并发问题 （支付宝特殊处理）
            if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
                logger.error("订单状态已被支付中心异步回调修改:"+newTbBizPlaceOrder.getPlaceOrderId());
                return;
            } else {
                throw new BizException("已退款订单不能重复退款");
            }
        }

        //包场子订单退款 更新父订单状态
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
        		&& PlaceConstants.ORDER_REFUND_STATUS.equals(newTbBizPlaceOrder.getOrderStatus())) {
        	placeOrderService.checkBlockOrder(tbBizPlaceOrder, PlaceConstants.ORDER_REFUND_STATUS , refundPrice);
        }

        //添加会员支付后退款(退到会员卡)
        boolean numCardRefund = false;//次卡退款标记
        int refundNum = 0;//次卡退款次数
        TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
        //获取会员卡
        TbBizPlaceMemberOpHistoryExample example = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNoEqualTo(reqPlaceOrderId);
        example.setOrderByClause(" id for update ");
        List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)) {
            String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
            if (!StringUtils.isEmpty(innerCardNo)) {
                TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
                TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
                tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
                tbBizPlaceMemberCardExample.setOrderByClause(" id for update ");
                List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
                tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
                if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
                    //次卡退款
                    tbBizPlaceMemberCard.setSurplusNumbers(tbBizPlaceMemberCard.getSurplusNumbers()+tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount());
                    numCardRefund = true;
                    refundNum = tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount();
                } else {
                    //储值，折扣卡，储值折扣卡退款
                    tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterAmount())));
                    tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterGiveAmount())));
                }
                int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
                if (flag1 == 1) {
                    TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
                    //退款生成订单号
                    String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, operateUid);
                    tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
                    tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList.get(0).getOrderNo());
                    tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
                    tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
                    tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
                    tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
                    tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceMemberOpHistoryList.get(0).getAmount());
                    tbBizPlaceMemberOpHistory.setCreateTime(new Date());
                    tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
                    tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
                    if (tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName().indexOf("抵扣") != -1){
                        tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName().replace("抵扣","退款"));
                    }else{
                        tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName() + "退款");
                    }
                    tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
                    tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
                    tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
                    tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
                    tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList.get(0).getMemo());
                    tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
                    tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
                    tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                    tbBizPlaceMemberOpHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterAmount())));
                    tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterGiveAmount())));
                    tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                    tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                    tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
                    tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
                    tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers()-(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeNumbers()-tbBizPlaceMemberOpHistoryList.get(0).getOpAfterNumbers()));
                    tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
                    if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
                        tbBizPlaceMemberOpHistory.setOpCardCount(tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount());
                    }
                    int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
                    if (flag2 != 1) {
                        throw new Exception("生成退款流水失败.");
                    }
                } else {
                    throw new Exception("修改会员卡失败.");
                }
            } else {
                throw new Exception("会员卡异常.");
            }
        } else {
            //包场子订单退款
            TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
            tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqPlaceOrderId);
            List<TbBizPlaceOrder> tbBizPlaceOrdersList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample1);
            if (!StringUtils.isEmpty(tbBizPlaceOrdersList.get(0).getParentId())){
                logger.debug("进入包场子订单退款流程");
                //根据子订单查询父订单
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrdersList.get(0).getParentId());
                String parentOrderId = tbBizPlacePrivateOrder.getPlaceOrderId();
                //获取会员卡
                TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
                TbBizPlaceMemberOpHistoryExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andOrderNoEqualTo(parentOrderId);
                List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList1 = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);
                if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList1)) {
                    String innerCardNo = tbBizPlaceMemberOpHistoryList1.get(0).getInnerCardNo();
                    if (!StringUtils.isEmpty(innerCardNo)) {
                        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
                        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
                        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
                        List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper
                                .selectByExample(tbBizPlaceMemberCardExample);
                        tbBizPlaceMemberCardExample.setOrderByClause(" id for update ");
                        tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
                        BigDecimal cardTypeInitGiveAmount = tbBizPlaceMemberCard.getGiveAmount();
                        BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
                        BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
                        //储值，折扣卡，储值折扣卡退款
                        if (tbBizPlaceMemberCard.getSurplusGiveAmount().compareTo(cardTypeInitGiveAmount) == -1){
                            //会员卡赠送金额 < 卡类型初始赠送金额  退到赠送
                            if (tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceOrdersList.get(0).getCredit()).compareTo(cardTypeInitGiveAmount) == 1){
                                //会员卡赠送余额+退款金额 > 卡类型初始金额
                                BigDecimal initSurplusGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
                                //赠送填满
                                tbBizPlaceMemberCard.setSurplusGiveAmount(cardTypeInitGiveAmount);
                                //剩余退到本金
                                tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceOrdersList.get(0).getCredit().subtract(cardTypeInitGiveAmount.subtract(initSurplusGiveAmount)));
                            }else{
                                //会员卡赠送余额+退款金额 <= 卡类型初始金额  直接退到赠送
                                tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceOrdersList.get(0).getCredit()));
                            }
                        }else {
                            //退款到本金
                            tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceOrdersList.get(0).getCredit()));
                        }
                        int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
                        if (flag1 == 1) {
                            TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
                            //退款生成订单号
                            String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, operateUid);
                            tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
                            tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList1.get(0).getOrderNo());
                            tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList1.get(0).getId());
                            tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList1.get(0).getCreateUid());
                            tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList1.get(0).getPlaceId());
                            tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
                            tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceOrdersList.get(0).getCredit());
                            tbBizPlaceMemberOpHistory.setCreateTime(new Date());
                            tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
                            tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList1.get(0).getPlaceId()));
                            tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList1.get(0).getOpTypeName() + "退款");
                            tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList1.get(0).getUid());
                            tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList1.get(0).getUserName());
                            tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList1.get(0).getMobile());
                            tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList1.get(0).getCardTypeName());
                            tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList1.get(0).getMemo());
                            tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
                            tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
                            tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                            tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
                            tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
                            tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                            tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
                            tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
                            tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList1.get(0).getCardTypeId());
                            tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberOpHistoryList1.get(0).getOpAfterNumbers());
                            tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberOpHistoryList1.get(0).getOpBeforeNumbers());

                            int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
                            if (flag2 != 1) {
                                throw new Exception("生成退款流水失败.");
                            }
                        } else {
                            throw new Exception("修改会员卡失败.");
                        }
                    } else {
                        throw new Exception("会员卡异常.");
                    }
                }
            } else {
                logger.debug("非会员退款.");
            }
        }

        //插入退款流水
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
            // do nothing
        }else {
            if (numCardRefund && refundNum > 0){
                ReqOrderHistory reqOrderHistory = placeOrderUtilService.memberTicket2ReqOrderHistory(newTbBizPlaceOrder,refundNum,(byte)1,(byte)0);
                placeOrderUtilService.insertOrderHistory(reqOrderHistory);
            }else {
                ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(newTbBizPlaceOrder,refundPrice,(byte)1,(byte)0);
                placeOrderUtilService.insertOrderHistory(reqOrderHistory);
            }
        }
    }
    
    /**
	 * 购物车订单扫码退款
	 * @param tbBizPlaceOrderItems
	 * @param tbBizPlaceOrder
	 * @param tbBizPlacePayItems
	 * @throws Exception
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public TbBizPlaceOrder shoppingCartOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
											  TbBizPlaceOrder tbBizPlaceOrder,
											  List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{
		if (CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
			return tbBizPlaceOrder;
		}

		TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);

		if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
				|| PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
			/**  扫码退款 **/
			tbBizPlaceOrder =placeOrderService.placeScanRefund(tbBizPlaceOrder, tbBizPlacePayItems, tbBizPlaceOrderItems, null);
		}
		//场地订单明细
		List<TbBizPlaceOrderItem> placeUnitOrderItemList = new ArrayList<>();;
		//门票订单明细
		List<TbBizPlaceOrderItem> placeTicketOrderItemList = new ArrayList<>();
		//小商品订单明细
		List<TbBizPlaceOrderItem> placeGoodsOrderItemList = new ArrayList<>();

		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
			//场地
			if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
					|| tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
					|| tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
				placeUnitOrderItemList.add(tbBizPlaceOrderItem);
			}
			//门票
			else if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
				placeTicketOrderItemList.add(tbBizPlaceOrderItem);
			}
			//小商品
			else if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
				placeGoodsOrderItemList.add(tbBizPlaceOrderItem);
			}
		}
		if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
				|| PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
			//修改支付明细为支出类型
			TbBizPlacePayItem payItemRecord = new TbBizPlacePayItem();
			payItemRecord.setAmountType(PlaceConstants.CREDIT_TYPE);
			TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
			tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId());
			tbBizPlacePayItemMapper.updateByExampleSelective(payItemRecord,tbBizPlacePayItemExample);

			if (!CollectionUtils.isEmpty(placeUnitOrderItemList)){
				//释放场地库存
				this.refundUpdateUnitSalePlan(placeUnitOrderItemList,PlaceConstants.PLACE_PREORDER_STATUS);
			}
			if (!CollectionUtils.isEmpty(placeTicketOrderItemList)){
				//修改门票统计
				placeTicketService.updateTicketStatistics(tbBizPlaceOrder, placeTicketOrderItemList);
			}
			if (!CollectionUtils.isEmpty(placeGoodsOrderItemList)){
				//增加商品库存
				placeGoodsService.addGoodsInventory(tbBizPlaceOrder,placeGoodsOrderItemList);
			}
		}
		if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
			if (!CollectionUtils.isEmpty(placeUnitOrderItemList)){
				//释放场地库存
				this.refundUpdateUnitSalePlan(placeUnitOrderItemList,PlaceConstants.PLACE_PREORDER_STATUS);
			}
			if (!CollectionUtils.isEmpty(placeTicketOrderItemList)){
				//修改门票统计
				placeTicketService.updateTicketStatistics(tbBizPlaceOrder, placeTicketOrderItemList);
			}
			if (!CollectionUtils.isEmpty(placeGoodsOrderItemList)){
				//增加商品库存
				placeGoodsService.addGoodsInventory(tbBizPlaceOrder,placeGoodsOrderItemList);
			}
		}
		return tbBizPlaceOrder;
	}
	
	
	/**
	 * 开单包场退款修改销售计划
	 * @param tbBizPlaceOrderItems
	 */
	public void refundUpdateUnitSalePlan(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,Byte status) throws Exception{
		List<String> saleIds = new ArrayList<>();
		for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
			saleIds.add(tbBizPlaceOrderItem.getSaleId());
		}
		TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
		example.createCriteria().andSaleIdIn(saleIds);
		List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = tbBizPlaceUnitSalePlanMapper
				.selectByExample(example);

		// 整点切换成半点时已预订的那部分销售计划
		TbBizPlaceUnitSalePlanExample example2 = new TbBizPlaceUnitSalePlanExample();
		example2.createCriteria().andDestSaleIdIn(saleIds);
		List<TbBizPlaceUnitSalePlan> halfTimeUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(example2);
		tbBizPlaceUnitSalePlans.addAll(halfTimeUnitSalePlans);

		List<UnitSalePlan> list = new ArrayList<>();
		for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
			UnitSalePlan up = new UnitSalePlan();
			up.setSaleId(tsp.getSaleId());
			list.add(up);
		}
		ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
		reqPlaceOrderListVo.setUnitSalePlanIdList(list);
		//reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);//退款——>销售计划状态改成可预订
		reqPlaceOrderListVo.setStatus(status);
		//int flag1 = placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
		int flag1 = placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);
	}
        private void adminBlockOrderRefund(TbBizPlaceOrder tbBizPlaceOrder,
								            List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
								            List<TbBizPlacePayItem> tbBizPlacePayItems,
								            String reqPlaceOrderId,
								            Integer operateUid) throws Exception{
    	
				if (tbBizPlaceOrder.getPayStatus().intValue() != PlaceConstants.PAY_STATUS.intValue()
				       && tbBizPlaceOrder.getOrderStatus().intValue() != PlaceConstants.ORDER_PAYED_STATUS){
				   throw new BizException("该订单未支付不能退款");
				}
				BigDecimal refundPrice = new BigDecimal(0);
				
				for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
				    refundPrice = refundPrice.add(tbBizPlaceOrderItem.getSalePrice());
				}
				//线下开单退款
				TbBizPlaceOrder newTbBizPlaceOrder = new TbBizPlaceOrder();
				BeanUtils.copyProperties(tbBizPlaceOrder, newTbBizPlaceOrder);
				//修改订单状态
				newTbBizPlaceOrder.setId(tbBizPlaceOrder.getId());
				newTbBizPlaceOrder.setPlaceOrderId(reqPlaceOrderId);
				newTbBizPlaceOrder.setOrderStatusChangeDate(new Date());
				/*BigDecimal credit = new BigDecimal(0);
				if (!StringUtils.isEmpty(tbBizPlaceOrder.getHandAdjustAmount())){
				credit = tbBizPlaceOrder.getDebit().add(tbBizPlaceOrder.getHandAdjustAmount());
				}else {
				credit = tbBizPlaceOrder.getDebit();
				}*/
				newTbBizPlaceOrder.setCredit(refundPrice);//退款金额
				newTbBizPlaceOrder.setRefundTime(new Date());//退款时间
				
				if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())
						|| PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
				//扫码退款  订单状态 = 退款中
					newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
				}else{
					newTbBizPlaceOrder.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
					newTbBizPlaceOrder.setPayStatus(PlaceConstants.REFUNDING_STATUS);
				}
				
				if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){//门票退款
				     newTbBizPlaceOrder = this.ticketOrderRefund(tbBizPlaceOrderItems, newTbBizPlaceOrder, tbBizPlacePayItems);
				     
				} else if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
				      || tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){//开单包场退款
				      newTbBizPlaceOrder = this.billingAndBlockOrderRefund(tbBizPlaceOrderItems,newTbBizPlaceOrder,tbBizPlacePayItems);
				      
				} else if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){//小商品退款
				    //小商品退款
				    newTbBizPlaceOrder = this.goodsOrderRefund(tbBizPlaceOrderItems, newTbBizPlaceOrder, tbBizPlacePayItems);
				    
				}
				
				try {
				     //退款日志
					TbBusinessLog log = new TbBusinessLog();
					log.setEntityId(tbBizPlaceOrder.getId());
					log.setEntityType(PlaceConstants.LOG_TYPE_PLACE_ORDER);
					log.setUid(operateUid);
					log.setLogName("商家端退款");
					log.setLogInfo("订单号：[" + tbBizPlaceOrder.getPlaceOrderId() + "]" + " 退款人：[" + tbBizPlaceOrder.getCustomerName() + "],订单金额：[" + tbBizPlaceOrder.getDebit() + "]" + "电话：[" + tbBizPlaceOrder.getMobile() + "]");
					tbBusinessLogService.insertLogInfo(log);
				} catch (Exception e) {
					throw new Exception("退款日志生成失败.");
				}

              TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
              TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
              tbBizPlaceOrderCriteria.andOrderStatusLessThanOrEqualTo(PlaceConstants.ORDER_REFUNDING_STATUS);
              tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(newTbBizPlaceOrder.getPlaceOrderId());
              TbBizPlaceOrder updateTbBizPlaceOrder = new TbBizPlaceOrder();
              BeanUtils.copyProperties(newTbBizPlaceOrder,updateTbBizPlaceOrder);
              updateTbBizPlaceOrder.setId(null);//设置为空，否则报Duplicate entry 'xxx' for key 'PRIMARY'
              if (this.tbBizPlaceOrderMapper.updateByExampleSelective(newTbBizPlaceOrder,tbBizPlaceOrderExample) == 0) {
                  //这里需要注意异步和同步同时到达并发问题 （支付宝特殊处理）
                  if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItems.get(0).getPayType().toString())){
                      logger.error("订单状态已被支付中心异步回调修改:"+newTbBizPlaceOrder.getPlaceOrderId());
                      return;
                  } else {
                      throw new BizException("已退款订单不能重复退款");
                  }
              }
				
				//包场子订单退款 更新父订单状态
				if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
							&& PlaceConstants.ORDER_REFUND_STATUS.equals(newTbBizPlaceOrder.getOrderStatus())) {
						placeOrderService.checkBlockOrder(tbBizPlaceOrder, PlaceConstants.ORDER_REFUND_STATUS , refundPrice);
				}
				
				//添加会员支付后退款(退到会员卡)
				boolean numCardRefund = false;//次卡退款标记
				int refundNum = 0;//次卡退款次数
				TbBizPlaceMemberCard tbBizPlaceMemberCard = null;
				//获取会员卡
				TbBizPlaceMemberOpHistoryExample example = new TbBizPlaceMemberOpHistoryExample();
				TbBizPlaceMemberOpHistoryExample.Criteria criteria = example.createCriteria();
				criteria.andOrderNoEqualTo(reqPlaceOrderId);
				example.setOrderByClause(" id for update ");
				
				List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example);
				if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)) {
					
					String innerCardNo = tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo();
				if (!StringUtils.isEmpty(innerCardNo)) {
					TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
					TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
					tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
					tbBizPlaceMemberCardExample.setOrderByClause(" id for update ");
					List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
					tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
				
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
					//次卡退款
					tbBizPlaceMemberCard.setSurplusNumbers(tbBizPlaceMemberCard.getSurplusNumbers()+tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount());
					numCardRefund = true;
					refundNum = tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount();
				} else {
					//储值，折扣卡，储值折扣卡退款
					tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterAmount())));
					tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterGiveAmount())));
				}
				int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
				if (flag1 == 1) {
					TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
					//退款生成订单号
					String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, operateUid);
					tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
					tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList.get(0).getOrderNo());
					tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList.get(0).getId());
					tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList.get(0).getCreateUid());
					tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId());
					tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
					tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceMemberOpHistoryList.get(0).getAmount());
					tbBizPlaceMemberOpHistory.setCreateTime(new Date());
					tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
					tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList.get(0).getPlaceId()));
				if (tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName().indexOf("抵扣") != -1){
					tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName().replace("抵扣","退款"));
				}else{
					tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName() + "退款");
				}
				tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList.get(0).getUid());
				tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
				tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
				tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
				tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList.get(0).getMemo());
				tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
				tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
				tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
				tbBizPlaceMemberOpHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterAmount())));
				tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryList.get(0).getOpAfterGiveAmount())));
				tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
				tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
				tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
				tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeId());
				tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers()-(tbBizPlaceMemberOpHistoryList.get(0).getOpBeforeNumbers()-tbBizPlaceMemberOpHistoryList.get(0).getOpAfterNumbers()));
				tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
				if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(tbBizPlaceMemberCard.getCardType())){
				  tbBizPlaceMemberOpHistory.setOpCardCount(tbBizPlaceMemberOpHistoryList.get(0).getOpCardCount());
				}
				int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
				if (flag2 != 1) {
				  throw new Exception("生成退款流水失败.");
					}
				} else {
						throw new Exception("修改会员卡失败.");
				}
				} else {
				throw new Exception("会员卡异常.");
				}
				} else {
					//包场子订单退款
					TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
					TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
					tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqPlaceOrderId);
					List<TbBizPlaceOrder> tbBizPlaceOrdersList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample1);
					if (!StringUtils.isEmpty(tbBizPlaceOrdersList.get(0).getParentId())){
					logger.debug("进入包场子订单退款流程");
					//根据子订单查询父订单
					TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrdersList.get(0).getParentId());
					String parentOrderId = tbBizPlacePrivateOrder.getPlaceOrderId();
					//获取会员卡
					TbBizPlaceMemberOpHistoryExample example1 = new TbBizPlaceMemberOpHistoryExample();
					TbBizPlaceMemberOpHistoryExample.Criteria criteria1 = example1.createCriteria();
					criteria1.andOrderNoEqualTo(parentOrderId);
					List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList1 = this.tbBizPlaceMemberOpHistoryMapper.selectByExample(example1);
				if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList1)) {
					String innerCardNo = tbBizPlaceMemberOpHistoryList1.get(0).getInnerCardNo();
					
				if (!StringUtils.isEmpty(innerCardNo)) {
				  TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
				  TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
				  tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(innerCardNo);
				  List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = this.tbBizPlaceMemberCardMapper
				          .selectByExample(tbBizPlaceMemberCardExample);
				  tbBizPlaceMemberCardExample.setOrderByClause(" id for update ");
				  tbBizPlaceMemberCard = tbBizPlaceMemberCardList.get(0);
				  BigDecimal cardTypeInitGiveAmount = tbBizPlaceMemberCard.getGiveAmount();
				  BigDecimal initAmount = tbBizPlaceMemberCard.getSurplusAmount();
				  BigDecimal initGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
				  //储值，折扣卡，储值折扣卡退款
				  if (tbBizPlaceMemberCard.getSurplusGiveAmount().compareTo(cardTypeInitGiveAmount) == -1){
				      //会员卡赠送金额 < 卡类型初始赠送金额  退到赠送
				      if (tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceOrdersList.get(0).getCredit()).compareTo(cardTypeInitGiveAmount) == 1){
				          //会员卡赠送余额+退款金额 > 卡类型初始金额
				          BigDecimal initSurplusGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount();
				          //赠送填满
				          tbBizPlaceMemberCard.setSurplusGiveAmount(cardTypeInitGiveAmount);
				          //剩余退到本金
				          tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceOrdersList.get(0).getCredit().subtract(cardTypeInitGiveAmount.subtract(initSurplusGiveAmount)));
				      }else{
				          //会员卡赠送余额+退款金额 <= 卡类型初始金额  直接退到赠送
				          tbBizPlaceMemberCard.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount().add(tbBizPlaceOrdersList.get(0).getCredit()));
				      }
				  }else {
				      //退款到本金
				      tbBizPlaceMemberCard.setSurplusAmount(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceOrdersList.get(0).getCredit()));
				  }
				  int flag1 = tbBizPlaceMemberCardMapper.updateByPrimaryKey(tbBizPlaceMemberCard);
				  if (flag1 == 1) {
				      TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
				      //退款生成订单号
				      String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, operateUid);
				      tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
				      tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList1.get(0).getOrderNo());
				      tbBizPlaceMemberOpHistory.setId(tbBizPlaceMemberOpHistoryList1.get(0).getId());
				      tbBizPlaceMemberOpHistory.setCreateUid(tbBizPlaceMemberOpHistoryList1.get(0).getCreateUid());
				      tbBizPlaceMemberOpHistory.setPlaceId(tbBizPlaceMemberOpHistoryList1.get(0).getPlaceId());
				      tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
				      tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceOrdersList.get(0).getCredit());
				      tbBizPlaceMemberOpHistory.setCreateTime(new Date());
				      tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
				      tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberOpHistoryList1.get(0).getPlaceId()));
				      tbBizPlaceMemberOpHistory.setOpTypeName(tbBizPlaceMemberOpHistoryList1.get(0).getOpTypeName() + "退款");
				      tbBizPlaceMemberOpHistory.setUid(tbBizPlaceMemberOpHistoryList1.get(0).getUid());
				      tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList1.get(0).getUserName());
				      tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList1.get(0).getMobile());
				      tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberOpHistoryList1.get(0).getCardTypeName());
				      tbBizPlaceMemberOpHistory.setMemo(tbBizPlaceMemberOpHistoryList1.get(0).getMemo());
				      tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard.getSurplusAmount());
				      tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
				      tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
				      tbBizPlaceMemberOpHistory.setOpBeforeAmount(initAmount);
				      tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(initGiveAmount);
				      tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
				      tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
				      tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
				      tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberOpHistoryList1.get(0).getCardTypeId());
				      tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberOpHistoryList1.get(0).getOpAfterNumbers());
				      tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberOpHistoryList1.get(0).getOpBeforeNumbers());
				
				      int flag2 = tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);
				      if (flag2 != 1) {
				          throw new Exception("生成退款流水失败.");
				      }
				  } else {
				      throw new Exception("修改会员卡失败.");
				  }
				} else {
				  throw new Exception("会员卡异常.");
				}
				}
				} else {
				logger.debug("非会员退款.");
				 }
				}
				if (numCardRefund && refundNum > 0){
					//插入退款流水
					ReqOrderHistory reqOrderHistory = placeOrderUtilService.memberTicket2ReqOrderHistory(newTbBizPlaceOrder,refundNum,(byte)1,(byte)0);
					placeOrderUtilService.insertOrderHistory(reqOrderHistory);
				}else {
					if (PlaceConstants.ORDER_REFUND_STATUS.equals(newTbBizPlaceOrder.getOrderStatus())
							&& PlaceConstants.REFUNDING_STATUS.equals(newTbBizPlaceOrder.getPayStatus())){
//			          	//明细转流水
//		    			List<ReqOrderHistory> reqOrderHistoryList = 
//		    					placeOrderUtilService.tbBizPlaceOrderItem2ReqOrderHistory(newTbBizPlaceOrder,tbBizPlaceOrderItems,(byte)1,(byte)0,tbBizPlaceMemberCard);
//		    			for (ReqOrderHistory reqOrderHistory : reqOrderHistoryList){
//		    				placeOrderUtilService.insertOrderHistory(reqOrderHistory);
//		    			}
		                ReqOrderHistory reqOrderHistory = placeOrderUtilService.tbBizPlaceOrder2ReqOrderHistory(newTbBizPlaceOrder,refundPrice,(byte)1,(byte)0);
		                placeOrderUtilService.insertOrderHistory(reqOrderHistory);
				 }
			}
		}
    /**
     * 门票订单退款
     * @param tbBizPlaceOrderItems
     * @param tbBizPlaceOrder
     * @param tbBizPlacePayItems
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private TbBizPlaceOrder ticketOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
                                              TbBizPlaceOrder tbBizPlaceOrder,
                                              List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{

        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);

        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
            /**  扫码退款 **/
            tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
        }
        if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
                || PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
            tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
            int flag = tbBizPlacePayItemMapper.updateByPrimaryKeySelective(tbBizPlacePayItem);
            if (flag !=1 ){
                throw new Exception("门票退款修改支付明细异常");
            }
            //修改门票统计
            placeTicketService.updateTicketStatistics(tbBizPlaceOrder, tbBizPlaceOrderItems);
        }
        if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
            //退款中，释放库存
            //修改门票统计
            placeTicketService.updateTicketStatistics(tbBizPlaceOrder, tbBizPlaceOrderItems);

        }
        return tbBizPlaceOrder;
    }

    /**
     * 商品订单退款
     * @param tbBizPlaceOrderItems
     * @param tbBizPlaceOrder
     * @param tbBizPlacePayItems
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private TbBizPlaceOrder goodsOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
                                             TbBizPlaceOrder tbBizPlaceOrder,
                                             List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{

        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);
        TbBizPlaceOrderItem tbBizPlaceOrderItem = tbBizPlaceOrderItems.get(0);

        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
            /**  扫码退款 **/
            tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
        }
        if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
                || PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
            tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
            int flag = tbBizPlacePayItemMapper.updateByPrimaryKeySelective(tbBizPlacePayItem);
            if (flag !=1 ){
                throw new Exception("商品退款修改支付明细异常");
            }
            //释放库存
            placeGoodsService.addGoodsInventory(tbBizPlaceOrder,tbBizPlaceOrderItems);
        }
        if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
            //退款中，释放库存
            placeGoodsService.addGoodsInventory(tbBizPlaceOrder, tbBizPlaceOrderItems);

        }
        return tbBizPlaceOrder;
    }

    /**
     * 开单包场散客退款
     * @param tbBizPlaceOrderItems
     * @param tbBizPlaceOrder
     * @param tbBizPlacePayItems
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private TbBizPlaceOrder billingAndBlockOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
                                                       TbBizPlaceOrder tbBizPlaceOrder,
                                                       List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{
        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);
        TbBizPlaceOrderItem tbBizPlaceOrderItem = tbBizPlaceOrderItems.get(0);
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
            /**  扫码退款 **/
            if (tbBizPlaceOrder.getUseType().byteValue() == PlaceConstants.ORDER_USE_BLOCK_BOOKING) {
                //包场退款
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper
                        .selectByPrimaryKey(tbBizPlaceOrder.getParentId());
                //针对包场订单部分付款（包场未成功，在开单处再进行支付）情况
                if (tbBizPlacePrivateOrder.getPayStatus().intValue() != PlaceConstants.PAY_STATUS.intValue()
                        && tbBizPlacePrivateOrder.getOrderStatus().intValue() != PlaceConstants.ORDER_PAYED_STATUS){
                    tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
                }else if (!StringUtils.isEmpty(tbBizPlaceOrder.getOrderNo())){
                    //兼容 包场预订再用扫码枪支付情况
                    tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
                }else{
                    //从父订单拿到下单信息（将父订单拆成多个子订单进行退款）
                    String childrenOrderId = tbBizPlaceOrder.getPlaceOrderId();//记录订单订单号，退款完重置子订单的订单号
                    //将父订单的退款依据给子订单
                    tbBizPlaceOrder.setOrderNo(tbBizPlacePrivateOrder.getOrderNo());
                    tbBizPlaceOrder.setPlaceOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());

                    tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,childrenOrderId);

                    tbBizPlaceOrder.setPlaceOrderId(childrenOrderId);//退款完重置子订单的订单号
                }
            }else{
                tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
            }
        }
        if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
                || PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
            //已退款，释放库存
            ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
            reqOrderOperate.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());

            placeOrderService.refundUpdateUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_PREORDER_STATUS);

        }
        if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
            //退款中，(需要锁定场地库存)释放库存
            ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
            reqOrderOperate.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());

            placeOrderService.refundUpdateUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_PREORDER_STATUS);

        }
        return tbBizPlaceOrder;
    }

    /**
     * 退场短信发送
     * @param placeOrderSalePlanList
     * @param uid
     * @param tbBizPlace
     * @return
     */
    @Async
    private boolean smsRefundSendOperate(List<PlaceOrderSalePlan> placeOrderSalePlanList,Integer uid, TbBizPlace tbBizPlace){
        if(CollectionUtils.isEmpty(placeOrderSalePlanList) ){
            return false;
        }
        List<String> mobileList=new ArrayList<>();
        List<String> paramList=new ArrayList<>();
        String [] args = new String[3];
        args[0] = "";
        args[1] = "";
        args[2] = "";

        Comparator<PlaceOrderSalePlan> comparator = new Comparator<PlaceOrderSalePlan>() {
            @Override
            public int compare(PlaceOrderSalePlan o1, PlaceOrderSalePlan o2) {
                return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

            }
        };
        Collections.sort(placeOrderSalePlanList, comparator);

        String salePlanDateNew = DateUtils.tranferStringToZHCN(placeOrderSalePlanList.get(0).getDate());
        args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + placeOrderSalePlanList.get(0).getCategoryId().toString());
        for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
            String startTime = placeOrderSalePlan.getStartTime();
            String endTime = placeOrderSalePlan.getEndTime();
            args[1] +=placeOrderSalePlan.getPlaceUnitName() + " " +  startTime.substring(0,startTime.length()-3) + "-" + endTime.substring(0,endTime.length()-3) + "、";
        }
        args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";

        //TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
        //args[2] = parameter.getParameterValue();
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            args[2]=placeAttach.getBookingConsultPhone();
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            args[2]=parameterVo!=null?parameterVo.getParameterValue():"";
        }

        APIResponse<RespUserInfoBase> userMsg = userServiceFacade.queryUserInfo(uid);
        if(!userMsg.isRet()){
            return false;
        }
        RespUserInfoBase respUserInfoBase = userMsg.getData();

        mobileList.add(respUserInfoBase.getMobile());
        paramList.addAll(Arrays.asList(args));
        //Result result = smsService.sendMessageToPhone(respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE,args,true);
        placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
        return true;
    }

    /**
     * 获取订单信息
     * @return
     */
    private TbBizPlaceOrder getBizPlaceOrder(String orderNo){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        tbBizPlaceOrderExampleCriteria.andIsEffectiveEqualTo((byte)1);//TODO 是否有效
        List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    /**
     * 包场获取子订单信息
     * @return
     */
    private TbBizPlaceOrder getBizPlaceOrderForBookAll(String orderNo){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    /**
     * 获取包场父订单信息
     * @return
     */
    private TbBizPlacePrivateOrder getBizPlacePrivateOrder(String orderNo){
        TbBizPlacePrivateOrderExample tbBizPlacePrivateOrderExample = new TbBizPlacePrivateOrderExample();
        TbBizPlacePrivateOrderExample.Criteria tbBizPlacePrivateOrderExampleCriteria = tbBizPlacePrivateOrderExample.createCriteria();
        tbBizPlacePrivateOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlacePrivateOrder> selectByExample = tbBizPlacePrivateOrderMapper.selectByExample(tbBizPlacePrivateOrderExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    /**
     * 获取会员卡充值信息
     * @return
     */
    private TbBizPlaceMemberOpHistory getBizPlaceMemberHistory(String orderNo){
        TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
        tbBizPlaceMemberOpHistoryExample.createCriteria().andOrderNoEqualTo(orderNo);
        //tbBizPlaceMemberOpHistoryExample.setOrderByClause(" id for update ");//加锁
        List<TbBizPlaceMemberOpHistory> selectByExample  = tbBizPlaceMemberOpHistoryMapper
                .selectByExample(tbBizPlaceMemberOpHistoryExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    @Override
    public APIResponse<?> pollingOrderStatus(String placeOrderId) {

        TbBizPlaceOrder tbBizPlaceOrder = new TbBizPlaceOrder();

        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        tbBizPlaceOrderExampleCriteria.andIsEffectiveEqualTo((byte)1);
        List<TbBizPlaceOrder> tbBizPlaceOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if (CollectionUtils.isEmpty(tbBizPlaceOrderList)){
            TbBizPlacePrivateOrderExample tbBizPlacePrivateOrderExample = new TbBizPlacePrivateOrderExample();
            TbBizPlacePrivateOrderExample.Criteria tbBizPlacePrivateOrderExampleCriteria = tbBizPlacePrivateOrderExample
                    .createCriteria();
            tbBizPlacePrivateOrderExampleCriteria.andPlaceOrderIdEqualTo(placeOrderId);
            List<TbBizPlacePrivateOrder> tbBizPlacePrivateOrderList = tbBizPlacePrivateOrderMapper
                    .selectByExample(tbBizPlacePrivateOrderExample);
            if (CollectionUtils.isEmpty(tbBizPlacePrivateOrderList)){
                TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
                tbBizPlaceMemberOpHistoryExample.createCriteria().andOrderNoEqualTo(placeOrderId);
                List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = tbBizPlaceMemberOpHistoryMapper
                        .selectByExample(tbBizPlaceMemberOpHistoryExample);
                if (CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
                    return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_IS_EMPTY);
                }
                if (tbBizPlaceMemberOpHistoryList.get(0).getState().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES)){
                    PlacePrintVo placePrintVo = new PlacePrintVo();
                    if (PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN.equals(tbBizPlaceMemberOpHistoryList.get(0).getSrc())){
                        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_OPEN_CARD);
                    }
                    if (PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE.equals(tbBizPlaceMemberOpHistoryList.get(0).getSrc())){
                        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_RECHARGE_CARD);
                    }
                    placePrintVo.setIsMember(PlaceConstants.NO);
                    placePrintVo.setPlaceOrderId(tbBizPlaceMemberOpHistoryList.get(0).getOrderNo());
                    return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
                }else if(tbBizPlaceMemberOpHistoryList.get(0).getState().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO)){
                    return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY);
                }
            }else{
                tbBizPlaceOrder.setOrderStatus(tbBizPlacePrivateOrderList.get(0).getOrderStatus());
                tbBizPlaceOrder.setPayStatus(tbBizPlacePrivateOrderList.get(0).getPayStatus());
                tbBizPlaceOrder.setUseType(tbBizPlacePrivateOrderList.get(0).getUseType());
                tbBizPlaceOrder.setPlaceOrderId(tbBizPlacePrivateOrderList.get(0).getPlaceOrderId());
                tbBizPlaceOrder.setParentId(tbBizPlacePrivateOrderList.get(0).getParentId());
            }
        }else{
            tbBizPlaceOrder = tbBizPlaceOrderList.get(0);
        }
        if (StringUtils.isEmpty(tbBizPlaceOrder)){
            return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_IS_EMPTY);
        }
        if (PlaceConstants.NOT_PAY_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
                || PlaceConstants.ORDER_PREPAY_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
            return APIResponse.returnFail(PlaceErrorCodeEnum.ORDER_WAIT_PAY);
        }
        PlacePrintVo placePrintVo = new PlacePrintVo();
        placePrintVo.setIsMember(PlaceConstants.NO);
        placePrintVo.setBusinessType(tbBizPlaceOrder.getUseType());
        if (tbBizPlaceOrder.getUseType().byteValue() == PlaceConstants.ORDER_USE_BLOCK_BOOKING && tbBizPlaceOrder.getParentId()==0){
            placePrintVo.setPlacePrivateOrderId(tbBizPlaceOrder.getPlaceOrderId());
        } else {
            placePrintVo.setPlaceOrderId(tbBizPlaceOrder.getPlaceOrderId());
        }
        return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
    }



    public  boolean getCombineSubSalePlanList(Integer placeId, TbBizPlaceUnitSalePlan combineSalePlan, List<TbBizPlaceUnitSalePlan> subSalePlanList)  {
        boolean valid = false;

        Byte unitType = combineSalePlan.getUnitType();
        if (unitType != null && UNIT_TYPE_BASE.equals(unitType)) {
            valid = false;
        } else {
            String subSaleplans = combineSalePlan.getSubSaleplans();
            if (subSaleplans == null || subSaleplans.isEmpty()) {
                TbBizPlaceUnitSalePlan tbCSP = null;
                if (combineSalePlan.getId() != null) {
                    tbCSP = puspMapper.selectByPrimaryKey(combineSalePlan.getId());
                } else if (combineSalePlan.getSaleId() != null) {
                    TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
                    TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
                    criteria.andPlaceIdEqualTo(placeId);
                    criteria.andSaleIdEqualTo(combineSalePlan.getSaleId());

                    List<TbBizPlaceUnitSalePlan> pusps = puspMapper.selectByExample(example);
                    if (pusps != null && pusps.size() > 0) {
                        tbCSP = pusps.get(0);
                    }
                }

                if (tbCSP != null) {
                    subSaleplans = tbCSP.getSubSaleplans();
                }
            }

            List<String> subSaleplanIds = new ArrayList<>();
            if (subSaleplans != null) {
                subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
            }

            // 从数据库中读取
            if (subSaleplanIds.size() > 0) {
                TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
                TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
                criteria.andPlaceIdEqualTo(placeId);
                criteria.andSaleIdIn(subSaleplanIds);
                List<TbBizPlaceUnitSalePlan> temp = puspMapper.selectByExample(example);
                if (temp != null) {
                    subSalePlanList.addAll(temp);
                }

                if (subSaleplanIds != null && subSalePlanList.size() == subSaleplanIds.size()) {
                    valid = true;
                }
            }
        }

        return valid;
    }


    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderPayConfirmOperate(ReqOrderOperate reqOrderOperate) {
        //需要进行权限限制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");

        }

        String orderNo = reqOrderOperate.getOrderNo();
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(orderNo);
        if (tbBizPlaceOrder != null){
            if (!tbBizPlaceOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                return APIResponse.returnFail("订单不是未支付状态！");
            }
        }
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = null;
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = null;
        if (tbBizPlaceOrder==null){
            tbBizPlacePrivateOrder = getBizPlacePrivateOrder(orderNo);
            if (tbBizPlacePrivateOrder!=null){
                if (!tbBizPlacePrivateOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlacePrivateOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                    return APIResponse.returnFail("订单不是未支付状态！");
                }
                //包场支付回调
                return placeOrderCallbackService.bookAllOrderCompletePayOperate(reqOrderOperate);
            }
            tbBizPlaceMemberOpHistory = getBizPlaceMemberHistory(orderNo);
            if (tbBizPlaceMemberOpHistory!=null){
                if (tbBizPlaceMemberOpHistory.getState().byteValue() != PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO && tbBizPlaceMemberOpHistory.getNo() != null){
                    return APIResponse.returnFail("开卡充值记录不是未支付状态！");
                }
                //商家端会员卡扫码支付充值回调
                if(MerchantClientPayType.getMatchScanPayType().containsKey(tbBizPlaceMemberOpHistory.getPayType().toString())){//update by tim
                    return placeOrderCallbackService.cardOrderCompletePayOperate(reqOrderOperate);
                }

            }
            return APIResponse.returnFail("没有该条订单信息！");
        }
        //商家端门票支付成功回调
        if (tbBizPlaceOrder.getSourceType().equals(PlaceConstants.SOURCE_TYPE_SCENEPAY)
                &&tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderCallbackService.ticketOrderCompletePayOperate(reqOrderOperate);
        }
        //商家端扫码开单包场回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                ||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
            return placeOrderCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderCallbackService.goodsOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderCallbackService.shoppingCartOrderCompletePayOperate(reqOrderOperate);
        }

        return APIResponse.returnFail("没有该条订单信息！");

    }

    @Override
    public APIResponse<?> orderSetterList(ReqOrderSetterVo reqOrderSetterVo) {
        return APIResponse.returnSuccess(placeOrderSetterService.orderSetterList(reqOrderSetterVo));
    }
    /**
     * 第三方场馆订单结算
     *任务调度
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor =Exception.class)
    public void orderSetterTask() {
        //获得第三方场馆
        //List<TbBizPlace> placeList = placeBaseService.getPoolPlace((byte)2, null, null);
        //获得最近的结算时间
        TbBizPlaceSetterDetail setterDetail= placeOrderSetterService.getMinOrMaxSetterDetailData(true,null);
      //  for (TbBizPlace place : placeList) {
            if (setterDetail!=null){
                Date day=setterDetail.getSetterTime();
                Date date=null;
                //上一次结算日期，跟当前时间前一天的区间
                    ReqOrderSetterVo vo = new ReqOrderSetterVo();
                    //vo.setPlaceId(place.getId());
                    vo.setOrderStatus((int) PlaceConstants.ORDER_COMPLETE_PAY_STATUS);
                    vo.setBusinessMode(2);
                    vo.setStartTime(DateUtils.getDateFormat(day));
                    vo.setEndTime(DateUtils.getDateFormat(new Date()));
                    List<RespOrderSetterVo> list = placeOrderSetterService.getPlaceOrderData(vo);
                    //存储要结算的订单
                    for (RespOrderSetterVo respVo : list) {
                        TbBizPlaceSetterDetail setterVo = new TbBizPlaceSetterDetail();
                        setterVo.setPlaceOrderId(respVo.getPlaceOrderId());
                        setterVo.setPayWay(respVo.getPayWay());
                        setterVo.setPlaceId(respVo.getPlaceId());
                        setterVo.setCategoryId(respVo.getCategoryId());
                        setterVo.setPlaceName(respVo.getPlaceName());
                        setterVo.setOrderStatus(respVo.getOrderStatus());
                        setterVo.setOrderFinishTime(respVo.getOrderFinishTime());
                        setterVo.setSetterTime(new Date());
                        setterVo.setOrderType(respVo.getOrderType());
                        setterVo.setSetterAmount(respVo.getSetterAmount());
                        setterVo.setSupplierId(respVo.getSupplierId());
                        setterVo.setPaymentTime(respVo.getPaymentTime());
                        //获取包场订单的orderNo
                        if (setterVo.getOrderType().intValue()==1){
                           TbBizPlacePrivateOrder priVo= placeOrderSetterService.getOrderNoById(respVo.getParentId());
                           setterVo.setOrderNo(priVo!=null?priVo.getOrderNo():null);
                        }else{
                            setterVo.setOrderNo(respVo.getOrderNo());
                        }
                        placeOrderSetterService.saveSetterOrderData(setterVo);
                    }
            }else{//结算今天之前的
                ReqOrderSetterVo vo = new ReqOrderSetterVo();
                //vo.setPlaceId(place.getId());
                vo.setOrderStatus((int) PlaceConstants.ORDER_COMPLETE_PAY_STATUS);
                vo.setBusinessMode(2);
                vo.setOrderFinishTime(new Date());
                //根据场馆ID 取出可以结算的订单(状态为已完成)
                List<RespOrderSetterVo> list = placeOrderSetterService.getPlaceOrderData(vo);
                //存储要结算的订单
                for (RespOrderSetterVo respVo : list) {
                    TbBizPlaceSetterDetail setterVo = new TbBizPlaceSetterDetail();
                    setterVo.setPlaceOrderId(respVo.getPlaceOrderId());
                    setterVo.setPayWay(respVo.getPayWay());
                    setterVo.setPlaceId(respVo.getPlaceId());
                    setterVo.setCategoryId(respVo.getCategoryId());
                    setterVo.setPlaceName(respVo.getPlaceName());
                    setterVo.setOrderStatus(respVo.getOrderStatus());
                    setterVo.setOrderFinishTime(respVo.getOrderFinishTime());
                    setterVo.setSetterTime(new Date());
                    setterVo.setOrderType(respVo.getOrderType());
                    setterVo.setSetterAmount(respVo.getSetterAmount());
                    setterVo.setSupplierId(respVo.getSupplierId());
                    setterVo.setPaymentTime(respVo.getPaymentTime());
                    //获取包场订单的orderNo
                    if (setterVo.getOrderType().intValue()==1){
                        TbBizPlacePrivateOrder priVo= placeOrderSetterService.getOrderNoById(respVo.getParentId());
                        setterVo.setOrderNo(priVo!=null?priVo.getOrderNo():null);
                    }else{
                        setterVo.setOrderNo(respVo.getOrderNo());
                    }
                    placeOrderSetterService.saveSetterOrderData(setterVo);
                }
            }
        }
   // }
    /**
     * 结算提现
     *R
     * @param reqOrderSetterVo
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse orderSetterOperate(ReqOrderSetterVo reqOrderSetterVo) {
        TbSupplier supplierVo=placeOrderSetterService.getBankAccountBySupplierId(reqOrderSetterVo.getSupplierId());
        if (supplierVo==null||supplierVo.getBcCardno()==null){
            return APIResponse.returnFail("供应商的银行账号不能为空号");
        }
        List<String> placeOrderIdList = new ArrayList<>();
        BigDecimal setterAmount=new BigDecimal("0");
        //取出要进行结算的订单
        List<TbBizPlaceSetterDetail> setterList = placeOrderSetterService.getSetterOrderDataBySupplierId(reqOrderSetterVo.getSupplierId(),0,null,null);
        for (TbBizPlaceSetterDetail detailVo:setterList){
            placeOrderIdList.add(detailVo.getPlaceOrderId());
            setterAmount=setterAmount.add(detailVo.getSetterAmount());
        }
        if(setterAmount.doubleValue()>0){
        //保存提现记录
        TbBizPlaceExtractRecord vo = new TbBizPlaceExtractRecord();
        vo.setUid(reqOrderSetterVo.getUid());
        vo.setBcbank(supplierVo.getBcBank());
        vo.setBccardno(supplierVo.getBcCardno());
        vo.setBcname(supplierVo.getBcName());
        vo.setExtractNo(reqOrderSetterVo.getSupplierId() + CommonUtils.generateToken(reqOrderSetterVo.getUid()));
        vo.setExtractTime(new Date());
        vo.setExtractAmount(setterAmount);
        vo.setStatus(1);
        vo.setSupplierId(reqOrderSetterVo.getSupplierId());
        List<TbBizPlaceSetterDetail> list = placeOrderSetterService.getSetterOrderDataBySupplierId(reqOrderSetterVo.getSupplierId(),1,null,null);
            TbBizPlaceSetterDetail detailVo=null;
            //没有结算过的订单
            if (list==null||list.size()<=0){
                List<TbBizPlaceSetterDetail> listVo = placeOrderSetterService.getSetterOrderDataBySupplierId(reqOrderSetterVo.getSupplierId(),0,null,null);
                detailVo=placeOrderSetterService.getMinOrMaxSetterDetailData(true,0);
                String dateStr=listVo!=null?DateUtils.changeDateToString(listVo.get(0).getOrderFinishTime(),1):"";
                //如果没有结算过的订单则取未结算的订单中最早的未结算订单完成时间，作为起始时间的收入
                vo.setRemark(dateStr+"-"+DateUtils.changeDateToString(DateUtils.getYestodayToDate(detailVo.getSetterTime()),1));
        }else{ //查询已经结算的订单的已结算最晚创建时间
                detailVo=placeOrderSetterService.getMinOrMaxSetterDetailData(true,1);
                TbBizPlaceSetterDetail  voVal=placeOrderSetterService.getMinOrMaxSetterDetailData(true,0);
                TbBizPlaceSetterDetail  voSettetDetail=placeOrderSetterService.getMinOrMaxSetterDetailData(false,0);
                int i= DateUtils.dateDiffDay(detailVo.getSetterTime(),voVal.getSetterTime());
                if (i>1){
                    vo.setRemark(DateUtils.changeDateToString(voSettetDetail.getSetterTime(),1)+"-"+DateUtils.changeDateToString(DateUtils.getYestodayToDate(voVal.getSetterTime()),1)+"收入");
                }else{
                    vo.setRemark(DateUtils.changeDateToString(DateUtils.getYestodayToDate(voVal.getSetterTime()),1)+"的收入");
                }
            }
            placeOrderSetterService.saveExtractRecordData(vo);
        //修改已经结算的订单状态改为已结算
        if (placeOrderIdList != null && placeOrderIdList.size() > 0) {
            placeOrderSetterService.updateSetterOrderStatus(placeOrderIdList);
        }
        //付款信息传递到财务系统
        ReqWithdrawApply drawVo=new ReqWithdrawApply();
        WithdrawPayInfo payInfo=new WithdrawPayInfo();
        payInfo.setApplyNo(vo.getExtractNo());
        payInfo.setAccountNo(vo.getBccardno());
        TbAdminUser user=adminUserService.getAdminUser(reqOrderSetterVo.getUid());
        payInfo.setName(supplierVo.getBcName());
        payInfo.setPhone(supplierVo.getPhone());
        payInfo.setRemark(vo.getRemark());
        payInfo.setBalance(new BigDecimal("0"));
        payInfo.setAmount(setterAmount);
        payInfo.setApplyTime(vo.getExtractTime());
        payInfo.setBusinessId(reqOrderSetterVo.getSupplierId());
        drawVo.setWithdrawPayInfo(payInfo);
        drawVo.setPayType(supplierVo.getBcId());
        drawVo.setNotifyUrl(supplierExtractUrl);
        drawVo.setSourceSystemCode(Constants.PLACE_SYSTEM_CODE);
        drawVo.setSourceBusinessCode(PlaceConstants.PLACE_SUPPLIER_EXTRACT_CODE);

        APIResponse apiResponse = orderPayService.applyWithdraw(drawVo);
        if (!apiResponse.isRet()){
            return apiResponse;
        }
        }else{
            return APIResponse.returnFail("没有可提现的余额");
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 提现列表
     * @param extractRecordVo
     * @return
     */
    @Override
    public APIResponse extractRecordList(ReqExtractRecordVo extractRecordVo) {
        return APIResponse.returnSuccess(placeOrderSetterService.extractRecordList(extractRecordVo));
    }

    /**
     * 第三方商家对账列表
     * @param reqVo
     * @return
     */
    @Override
    public APIResponse businessCheckAccount(ReqBusinessAccountVo reqVo) {
        RespBusinessAccountVo respVo=new RespBusinessAccountVo();
        List<RespBusinessAccountVo> accountVolist=new ArrayList<>();

        BigDecimal totalAmount = new BigDecimal(0);//收入总金额
        BigDecimal totalPayAmount = new BigDecimal(0);//已付总金额
        BigDecimal totalShouldAmount = new BigDecimal(0);//应付总金额
        Date startTiem=null;
        Date endTime=null;
        if (reqVo!=null){
        if (reqVo.getStartTime()!=null){
            startTiem= DateUtils.getDateFormat(reqVo.getStartTime());
        }
        if (reqVo.getEndTime()!=null){
            endTime=DateUtils.getDateFormat(reqVo.getEndTime());
        }
        if (!StringUtils.isEmpty(reqVo.getSupplierName())){
            reqVo.setSupplierName("%"+reqVo.getSupplierName().trim()+"%");
        }else{
            reqVo.setSupplierName(null);
        }
        }
        reqVo.setBusinessMode(2);
       // int total = placeOrderSetterService.getPlaceSupplierCount(reqVo);
        List<TbSupplier> listSupplier = placeOrderSetterService.getPlaceSupplier(reqVo,true);
        //根据场馆ID查找收入金额，已付金额,应付金额累加
        List<Integer> statusList = new ArrayList<>();
        statusList.add(2);
        for (TbSupplier vo : listSupplier) {
            BigDecimal amount = new BigDecimal(0);//收入金额
            BigDecimal payAmount = new BigDecimal(0);//已付金额
            BigDecimal shouldAmount = new BigDecimal(0);//应付金额
            RespBusinessAccountVo accountVo=new RespBusinessAccountVo();
            //取出供应商所属场馆的收入金额,已付金额,应付金额
            //获得收入金额
            List<TbBizPlaceSetterDetail> listValue = placeOrderSetterService.getSetterOrderDataBySupplierId(vo.getId(), null,startTiem,endTime);
            for (TbBizPlaceSetterDetail detail : listValue) {
                amount = amount.add(detail.getSetterAmount());
            }
            //获得已付金额
            List<TbBizPlaceExtractRecord> listRecord = placeOrderSetterService.getExtractRecordListBySupplierId(vo.getId(), statusList,startTiem,endTime);
            for (TbBizPlaceExtractRecord record : listRecord) {
                payAmount = payAmount.add(record.getExtractAmount());
            }
            //应付金额=收入金额-已付金额
            shouldAmount = amount.subtract(payAmount);
            accountVo.setSupplierId(vo.getId());
            accountVo.setCityId(vo.getCityId());
            accountVo.setSupplierName(vo.getName());
            accountVo.setAmount(amount);
            accountVo.setPayAmount(payAmount);
            accountVo.setShouldAmount(shouldAmount);
            //如果供应商没有第三方订单就不做展示
            if (listValue!=null&&listValue.size()>0){
                accountVolist.add(accountVo);
            }
          /*  totalAmount=totalAmount.add(amount);
            totalPayAmount=totalPayAmount.add(payAmount);
            totalShouldAmount=totalShouldAmount.add(shouldAmount);*/
        }
        PageObj<List<RespBusinessAccountVo>> result = PageObj.create(accountVolist.size(), reqVo.getPageNum(), reqVo.getPageSize(), accountVolist);
        List<TbSupplier> list = placeOrderSetterService.getPlaceSupplier(reqVo,false);
        for (TbSupplier voVal : list) {
            //获得收入金额
            List<TbBizPlaceSetterDetail> listValue = placeOrderSetterService.getSetterOrderDataBySupplierId(voVal.getId(), null,startTiem, endTime);
            for (TbBizPlaceSetterDetail detail : listValue) {
                totalAmount = totalAmount.add(detail.getSetterAmount());
            }
            //获得已付金额
            List<TbBizPlaceExtractRecord> listRecord = placeOrderSetterService.getExtractRecordListBySupplierId(voVal.getId(), statusList,startTiem, endTime);
            for (TbBizPlaceExtractRecord record : listRecord) {
                totalPayAmount = totalPayAmount.add(record.getExtractAmount());
            }
        }
        totalShouldAmount=totalAmount.subtract(totalPayAmount);
        respVo.setTotalAmount(totalAmount);
        respVo.setTotalPayAmount(totalPayAmount);
        respVo.setTotalShouldAmount(totalShouldAmount);
        respVo.setResult(result);
        return APIResponse.returnSuccess(respVo);
    }

    /**
     * 根据供应商ID获取商家银行卡账号，
     * @param supplierId
     * @return
     */
    @Override
    public APIResponse getAccountInfoByPlaceId(Integer supplierId) {
        TbSupplier vo= placeOrderSetterService.getBankAccountBySupplierId(supplierId);
        BigDecimal setterTotalAmount = new BigDecimal(0);
        //取出要进行结算的订单
            List<TbBizPlaceSetterDetail> list = placeOrderSetterService.getSetterOrderDataBySupplierId(supplierId,0,null,null);
            for (TbBizPlaceSetterDetail detail : list) {
                setterTotalAmount = setterTotalAmount.add(detail.getSetterAmount());
            }
        RespOrderSetterVo resp=new RespOrderSetterVo();
        resp.setSupplierId(vo.getId());
        resp.setSetterAmount(setterTotalAmount);
        resp.setBcBank(vo.getBcBank());
        resp.setBcCardno(vo.getBcCardno());
        resp.setBcName(vo.getBcName());
        return APIResponse.returnSuccess(resp);
    }

    /**
     * 根据供应商获得场馆
     * @param supplierId
     * @returnRp
     */
    public APIResponse getPlaceBySupplierId(Integer supplierId){
        return APIResponse.returnSuccess(placeInnerService.getPlaceBySupplierId(supplierId));
    }

    @Override
    public APIResponse updateExtractInfoByExtractNo(ExtractCallBackVo extractVo) {
       return APIResponse.returnSuccess(placeOrderSetterService.updateExtractInfoByExtractNo(extractVo));
    }

    /** 购物车订单详情展示 **/
    @Override
    public APIResponse getPlaceOrderDetail(String placeOrderId) {
        TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
        tbBizPlaceOrderItemExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItemList = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
        List<GoodsInfo> goodsInfoList = new ArrayList<>();
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        tbBizPlaceOrderExample.createCriteria().andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrder> tbBizPlaceOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if (CollectionUtils.isEmpty(tbBizPlaceOrderList)) {
            return APIResponse.returnFail("查无此订单");
        }
        TbBizPlaceOrder tbBizPlaceOrder = tbBizPlaceOrderList.get(0);
        //订单应付金额
        BigDecimal payableAmount = new BigDecimal(0);

        if (CollectionUtils.isNotEmpty(tbBizPlaceOrderItemList)){
            for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItemList){
                GoodsInfo goodsInfo = new GoodsInfo();
                BeanUtils.copyProperties(tbBizPlaceOrderItem,goodsInfo);
                Integer count = (StringUtils.isEmpty(tbBizPlaceOrderItem.getTotalGoodsCount()) ? 0 : tbBizPlaceOrderItem.getTotalGoodsCount())
                        - (StringUtils.isEmpty(tbBizPlaceOrderItem.getSurplusGoodsCount()) ? 0 : tbBizPlaceOrderItem.getSurplusGoodsCount());
                if (count > 0){
                    //该明细产生退款
                    goodsInfo.setRefundStatus(PlaceConstants.YES.intValue());
                }
                //兼容历史订单明细查询  goodsType;//0:场地 1:小商品 2：门票
                if (StringUtils.isEmpty(tbBizPlaceOrderItem.getUseType())){
                    //场地
                    if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                            || tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
                            || tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
                        goodsInfo.setGoodsType(0);

                        TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = tbBizPlaceUnitSalePlanMapper
                                .selectByPrimaryKey(tbBizPlaceOrderItem.getUnitSalePlanId());
                        goodsInfo.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
                        goodsInfo.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
                        goodsInfo.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());

                        goodsInfo.setCategoryId(tbBizPlaceOrder.getId());
                    }
                    //小商品
                    else if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
                        goodsInfo.setGoodsType(1);
                        //查询小商品规格
                        TbBizPlaceGoodsInfoExample tbBizPlaceGoodsInfoExample = new TbBizPlaceGoodsInfoExample();
                        TbBizPlaceGoodsInfoExample.Criteria tbBizPlaceGoodsInfoCriteria = tbBizPlaceGoodsInfoExample.createCriteria();
                        tbBizPlaceGoodsInfoCriteria.andGoodsIdEqualTo(tbBizPlaceOrderItem.getSaleId());
                        List<TbBizPlaceGoodsInfo> tbBizPlaceGoodsInfoList = tbBizPlaceGoodsInfoMapper.selectByExample(tbBizPlaceGoodsInfoExample);
                        if (CollectionUtils.isNotEmpty(tbBizPlaceGoodsInfoList)){
                            goodsInfo.setGoodsStandard(tbBizPlaceGoodsInfoList.get(0).getGoodsStandard());
                        }
                        goodsInfo.setTotalGoodsCount(tbBizPlaceOrderItem.getTicketCount());
                    }
                    //门票
                    else if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
                        goodsInfo.setGoodsType(2);

                        TbPlaceTicketSalePlan tbPlaceTicketSalePlan = tbPlaceTicketSalePlanMapper
                                .selectByPrimaryKey(tbBizPlaceOrderItem.getUnitSalePlanId());
                        goodsInfo.setGoodsName(tbPlaceTicketSalePlan.getTicketName());
                        goodsInfo.setStartTime(tbPlaceTicketSalePlan.getStartTime());
                        goodsInfo.setEndTime(tbPlaceTicketSalePlan.getEndTime());

                        goodsInfo.setCategoryId(tbBizPlaceOrder.getId());
                    }

                }else{
                    //场地
                    if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                            || tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)
                            || tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
                        goodsInfo.setGoodsType(0);
                    }
                    //小商品
                    else if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
                        goodsInfo.setGoodsType(1);
                    }
                    //门票
                    else if (tbBizPlaceOrderItem.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
                        goodsInfo.setGoodsType(2);
                    }
                }

                goodsInfoList.add(goodsInfo);
                payableAmount = payableAmount.add(tbBizPlaceOrderItem.getSalePrice());
            }
        }

        RespOrderDetail respOrderDetail = new RespOrderDetail();
        respOrderDetail.setGoodsInfo(goodsInfoList);
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(tbBizPlaceOrder,orderInfo);
        if (!StringUtils.isEmpty(tbBizPlaceOrder.getInnerCardNo())){
            TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardByInnerCardNo(tbBizPlaceOrder.getInnerCardNo());
            orderInfo.setTbBizPlaceMemberCard(tbBizPlaceMemberCard);
        }

        orderInfo.setOrderAmount(tbBizPlaceOrder.getDebit());
        orderInfo.setPayableAmount(payableAmount.compareTo(BigDecimal.ZERO) == 0?null:payableAmount);
        if (tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
            orderInfo.setPayAmount(null);
        }else{
            Map<String, Object> map = new HashMap();
            List<String> listPlaceOrderId = new ArrayList<>();
            listPlaceOrderId.add(tbBizPlaceOrder.getPlaceOrderId());
            map.put("placeOrderId", listPlaceOrderId);
            BigDecimal payAmount = financeCommonManagerMapper.getDiscountAmount(map);
            if (StringUtils.isEmpty(payAmount)){
                payAmount = BigDecimal.ZERO;
            }
            orderInfo.setPayAmount(payAmount);
        }

        Map<String,Object> params=new HashMap<>();
        params.put("placeOrderId",tbBizPlaceOrder.getPlaceOrderId() );
        List<RespPlaceOrderDiscountItem> respPlaceOrderDiscountItemList = placeOrderAdminMapper.getOrderDiscount(params);
        if (CollectionUtils.isNotEmpty(respPlaceOrderDiscountItemList)){
            RespPlaceOrderDiscountItem discountResult = respPlaceOrderDiscountItemList.get(0);
            if (!StringUtils.isEmpty(discountResult)){
                orderInfo.setAdjustDiscountAmount(discountResult.getDiscountAdjust());
                BigDecimal memberDiscountAmount = StringUtils.isEmpty(discountResult.getDiscountMember())?BigDecimal.ZERO:discountResult.getDiscountMember()
                        .add(StringUtils.isEmpty(discountResult.getDiscountDiscountMember())?BigDecimal.ZERO:discountResult.getDiscountDiscountMember())
                        .add(StringUtils.isEmpty(discountResult.getDiscountNumberMember())?BigDecimal.ZERO:discountResult.getDiscountNumberMember());
                BigDecimal couponDiscountAmount = StringUtils.isEmpty(discountResult.getDiscountCoupon())?BigDecimal.ZERO:discountResult.getDiscountCoupon()
                        .add(StringUtils.isEmpty(discountResult.getDiscountDiscountCoupon())?BigDecimal.ZERO:discountResult.getDiscountDiscountCoupon());
                orderInfo.setMemberDiscountAmount(memberDiscountAmount.compareTo(BigDecimal.ZERO) == 0?null:memberDiscountAmount);
                orderInfo.setCouponDiscountAmount(couponDiscountAmount.compareTo(BigDecimal.ZERO) == 0?null:couponDiscountAmount);
                orderInfo.setEggDiscountAmount(discountResult.getDiscountEgg());
            }/*else{
                //没有优惠信息的包场订单只显示实付金额
                if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
                    orderInfo.setOrderAmount(null);
                    orderInfo.setPayableAmount(null);
                }
            }*/
        }

        /*** 支付方式 **/
        List<Integer> tbBizPlacePayIdList = tbBizPlaceOrderManagerMapper.selectPayTypeGroupByPayType(placeOrderId);
        /*if (CollectionUtils.isNotEmpty(tbBizPlacePayIdList)){
            List<String> payTypeList = new ArrayList<>();
            for (Integer payId : tbBizPlacePayIdList){
                payTypeList.add(payId.toString());
            }
            Map paraMap = new HashMap();
            paraMap.put("payTypeList",payTypeList);
            List<String> payTypeStr = tbBizPlaceOrderManagerMapper.selectPayTypeByPayIds(paraMap);

            StringBuilder sb = new StringBuilder();
            for (String payType : payTypeStr){
                sb.append(payType).append("/");
            }
            sb.deleteCharAt(sb.length() - 1);
            orderInfo.setPayType(sb.toString());
        }*/
        orderInfo.setPayType(tbBizPlacePayIdList);


        respOrderDetail.setOrderInfo(orderInfo);
        return APIResponse.returnSuccess(respOrderDetail);
    }


    public static void main(String[] args) {
        BigDecimal s = new BigDecimal(150);
        BigDecimal s1 = new BigDecimal(150.0);
        if (s.compareTo(s1) >= 0){
            System.out.printf("1=================="+s.compareTo(s1)+"========");
        }else{
            System.out.printf("2=================="+s.compareTo(s1));
        }

    }
}
